package main

import (
	"os"

	"git.solsynth.dev/goatworks/turbine/pkg/launchpad/config"
	"git.solsynth.dev/goatworks/turbine/pkg/launchpad/deploy"
	"git.solsynth.dev/goatworks/turbine/pkg/launchpad/dev"
	"git.solsynth.dev/goatworks/turbine/pkg/launchpad/interactive"
	"github.com/joho/godotenv"
	"github.com/rs/zerolog"
	"github.com/rs/zerolog/log"
)

func init() {
	// Initialize logging
	log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr, TimeFormat: "15:04:05"})
}

func main() {
	// Load .env file if it exists
	if err := godotenv.Load(); err != nil {
		log.Info().Msg("No .env file found, relying on environment variables.")
	}

	// Check for command-line arguments
	if len(os.Args) < 2 {
		log.Fatal().Msg("Usage: launchpad <command>\nCommands: dev, deploy")
	}

	// Load the main launchpad configuration
	cfg := config.Load()
	command := os.Args[1]

	// Dispatch to the correct handler
	switch command {
	case "dev":
		handleDev(cfg, os.Args[2:])
	case "deploy":
		log.Info().Msg("Generating docker-compose.yml for production deployment...")
		deploy.GenerateDockerCompose(cfg)
	default:
		log.Fatal().Msgf("Unknown command: %s", command)
	}
}

func handleDev(cfg config.LaunchpadConfig, args []string) {
	var servicesToRun []config.Service

	if len(args) == 0 {
		// Interactive mode
		selectedServices, err := interactive.SelectServices(cfg.Services)
		if err != nil {
			log.Fatal().Err(err).Msg("Could not start interactive selection")
		}
		if len(selectedServices) == 0 {
			log.Info().Msg("No services selected. Exiting.")
			return
		}
		servicesToRun = selectedServices
	} else if len(args) == 1 && args[0] == "all" {
		log.Info().Msg("Starting all services.")
		servicesToRun = cfg.Services
	} else {
		// Start specific services from args
		serviceMap := make(map[string]config.Service)
		for _, s := range cfg.Services {
			serviceMap[s.Name] = s
		}

		for _, arg := range args {
			if service, ok := serviceMap[arg]; ok {
				servicesToRun = append(servicesToRun, service)
			} else {
				log.Fatal().Msgf("Service '%s' not found in launchpad.toml", arg)
			}
		}
	}

	if len(servicesToRun) > 0 {
		dev.RunDev(cfg, servicesToRun)
	}
}
