package main

import (
	"context" // Added for graceful shutdown
	"flag"
	"fmt"
	"log"
	"os"
	"os/signal" // Added for graceful shutdown
	"syscall"   // Added for graceful shutdown
	"time"      // Added for graceful shutdown

	"git.linuxforward.com/byop/byop-engine/analyzer"
	"git.linuxforward.com/byop/byop-engine/analyzer/stacks/golang"
	"git.linuxforward.com/byop/byop-engine/analyzer/stacks/nodejs"
	"git.linuxforward.com/byop/byop-engine/analyzer/stacks/python"
	"git.linuxforward.com/byop/byop-engine/app"
	"git.linuxforward.com/byop/byop-engine/config"
)

// Version information
var (
	Version   = "0.1.0"
	BuildTime = "unknown"
	GitCommit = "unknown"
)

func printVersion() {
	fmt.Printf("BYOP Engine v%s\n", Version)
	fmt.Printf("Build time: %s\n", BuildTime)
	fmt.Printf("Git commit: %s\n", GitCommit)
}

func printHelp() {
	fmt.Printf("BYOP Engine - Bring Your Own Platform engine\n\n")
	fmt.Printf("Usage: %s [options]\n\n", os.Args[0])
	fmt.Println("Options:")
	flag.PrintDefaults()
}

func main() {
	// 1. Parse command line flags
	configPath := flag.String("config", "./config.yaml", "Path to configuration file")
	showVersion := flag.Bool("version", false, "Display version information and exit")
	showHelp := flag.Bool("help", false, "Display help information and exit")
	flag.Parse()

	// Handle version and help flags
	if *showVersion {
		printVersion()
		os.Exit(0)
	}

	if *showHelp {
		printHelp()
		os.Exit(0)
	}

	// 2. Parse and validate configuration
	cfg, err := config.Load(*configPath)
	if err != nil {
		log.Fatalf("Failed to load configuration: %v", err)
	}
	if err := cfg.Validate(); err != nil {
		log.Fatalf("Configuration validation failed: %v", err)
	}

	// Register analyzer stacks
	analyzer.RegisterStack(&golang.Golang{})
	analyzer.RegisterStack(&nodejs.NodeJS{})
	analyzer.RegisterStack(&python.Python{})
	log.Println("Registered analyzer stacks: Go, NodeJS, Python")

	// 3. Initialize application
	appInstance, err := app.NewApp(cfg) // Renamed to avoid conflict with package name
	if err != nil {
		log.Fatalf("Failed to initialize application: %v", err)
	}

	// 4. Start application in a goroutine
	go func() {
		if err := appInstance.Run(); err != nil {
			log.Printf("Error starting application: %v", err) // Use Printf for non-fatal errors in goroutines
		}
	}()

	// 5. Implement graceful shutdown
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit // Block until a signal is received

	log.Println("Shutting down server...")

	// Create a context with a timeout for the shutdown
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) // 30-second timeout for shutdown
	defer cancel()

	if err := appInstance.Shutdown(ctx); err != nil {
		log.Fatalf("Server shutdown failed: %v", err)
	}

	log.Println("Server gracefully stopped")
}
