package cmd

import (
	"fmt"
	"os"

	"github.com/insertr/insertr/internal/config"
	"github.com/spf13/cobra"
)

var (
	configFile string
	dbPath     string
	apiURL     string
	apiKey     string
	siteID     string
	loader     config.Loader
)

var rootCmd = &cobra.Command{
	Use:   "insertr",
	Short: "Insertr - The Tailwind of CMS",
	Long: `Insertr adds editing capabilities to static HTML sites by detecting 
editable elements and injecting content management functionality.

The unified tool handles both build-time content injection (enhance command)
and runtime API server (serve command) for complete CMS functionality.`,
	Version: "0.1.0",
}

func Execute() {
	if err := rootCmd.Execute(); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}

func init() {
	loader = config.NewLoader()

	// Global flags
	rootCmd.PersistentFlags().StringVar(&configFile, "config", "", "config file (default is ./insertr.yaml)")
	rootCmd.PersistentFlags().StringVar(&dbPath, "db", "", "database path (SQLite file or PostgreSQL connection string)")
	rootCmd.PersistentFlags().StringVar(&apiURL, "api-url", "", "content API URL")
	rootCmd.PersistentFlags().StringVar(&apiKey, "api-key", "", "API key for authentication")
	rootCmd.PersistentFlags().StringVarP(&siteID, "site-id", "s", "", "site ID for content lookup")

	rootCmd.AddCommand(enhanceCmd)
	rootCmd.AddCommand(serveCmd)
}

func loadConfig() (*config.Config, error) {
	if configFile != "" || dbPath != "" || apiURL != "" || apiKey != "" || siteID != "" {
		return loader.LoadWithFlags(dbPath, apiURL, apiKey, siteID)
	}
	return loader.Load(configFile)
}
