package cmd

import (
	"fmt"
	"log"
	"time"

	"github.com/spf13/cobra"

	"codeberg.org/mapleopentech/monorepo/cloud/maplefile-backend/app"
	"codeberg.org/mapleopentech/monorepo/cloud/maplefile-backend/config"
)

// formatBuildTime converts ISO 8601 timestamp to human-readable 12-hour format
func formatBuildTime(isoTime string) string {
	t, err := time.Parse(time.RFC3339, isoTime)
	if err != nil {
		return isoTime // Return original if parsing fails
	}
	return t.Format("Jan 2, 2006 3:04:05 PM MST")
}

var daemonCmd = &cobra.Command{
	Use:   "daemon",
	Short: "Start the MapleFile backend server",
	Long:  `Start the MapleFile backend HTTP server and listen for requests.`,
	Run:   runDaemon,
}

func runDaemon(cmd *cobra.Command, args []string) {
	// Validate configuration on startup
	cfg, err := config.Load()
	if err != nil {
		log.Fatalf("Failed to load configuration: %v", err)
	}

	if err := cfg.Validate(); err != nil {
		log.Fatalf("Invalid configuration: %v", err)
	}

	fmt.Printf("🚀 Starting MapleFile Backend v%s\n", version)
	fmt.Printf("📝 Git Commit: %s\n", gitCommit)
	fmt.Printf("🕐 Build Time: %s\n", formatBuildTime(buildTime))
	fmt.Printf("📝 Environment: %s\n", cfg.App.Environment)
	fmt.Printf("🌐 Server will listen on %s:%d\n", cfg.Server.Host, cfg.Server.Port)

	// Create and run the Wire-based application
	application, err := app.InitializeApplication(cfg)
	if err != nil {
		log.Fatalf("Failed to initialize application: %v", err)
	}

	// Start the application
	// Wire application handles lifecycle and graceful shutdown
	if err := application.Start(); err != nil {
		log.Fatalf("Application terminated with error: %v", err)
	}

	fmt.Println("👋 Server stopped gracefully")
}
