package main

import (
	"embed"
	"flag"
	"fmt"
	"log"
	"os"
	"os/signal"
	"syscall"

	"ci/internal/server"
)

//go:embed web/dist
var frontend embed.FS

func main() {
	port := flag.String("port", "8080", "HTTP server port")
	dataDir := flag.String("data", "data", "Data directory path")
	flag.Parse()

	// Check if frontend is embedded (non-empty)
	var embeddedFS *embed.FS
	if _, err := frontend.ReadDir("web/dist"); err == nil {
		embeddedFS = &frontend
		fmt.Println("Using embedded frontend")
	} else {
		fmt.Println("Embedded frontend not found, using dev mode (web/dist)")
	}

	config := server.Config{
		Port:    *port,
		DataDir: *dataDir,
	}

	srv, err := server.New(config, embeddedFS)
	if err != nil {
		log.Fatalf("Failed to create server: %v", err)
	}

	// Graceful shutdown on interrupt
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	go func() {
		<-quit
		fmt.Println("\nShutting down...")
		srv.Shutdown()
		os.Exit(0)
	}()

	fmt.Printf("CI/CD Server starting on http://localhost:%s\n", config.Port)
	if err := srv.Run(); err != nil {
		log.Fatalf("Server error: %v", err)
	}
}
