package cmd

import (
	"fmt"
	"log"
	"os"
	"path/filepath"
	"strings"

	"github.com/spf13/cobra"
	"github.com/spf13/viper"

	"github.com/insertr/insertr/internal/content"
	"github.com/insertr/insertr/internal/db"
	"github.com/insertr/insertr/internal/engine"
)

var enhanceCmd = &cobra.Command{
	Use:   "enhance [input-path]",
	Short: "Enhance HTML files by injecting content from database",
	Long: `Enhance processes HTML files and injects latest content from the database
while adding editing capabilities. This is the core build-time enhancement
process that transforms static HTML into an editable CMS.

The input can be either a directory (to enhance all HTML files) or a single
HTML file. Non-HTML files in directories are copied as-is.`,
	Args: cobra.ExactArgs(1),
	Run:  runEnhance,
}

var (
	outputDir string
)

func init() {
	enhanceCmd.Flags().StringVarP(&outputDir, "output", "o", "./dist", "Output directory for enhanced files")

	// Bind flags to viper
	viper.BindPFlag("cli.output", enhanceCmd.Flags().Lookup("output"))
}

func runEnhance(cmd *cobra.Command, args []string) {
	inputPath := args[0]

	// Validate input path and determine if it's a file or directory
	inputStat, err := os.Stat(inputPath)
	if os.IsNotExist(err) {
		log.Fatalf("Input path does not exist: %s", inputPath)
	}
	if err != nil {
		log.Fatalf("Error accessing input path: %v", err)
	}

	isFile := !inputStat.IsDir()
	if isFile {
		// Validate that single files are HTML files
		if !strings.HasSuffix(strings.ToLower(inputPath), ".html") {
			log.Fatalf("Single file input must be an HTML file (.html extension): %s", inputPath)
		}
	}

	// Get configuration values
	dbPath := viper.GetString("database.path")
	apiURL := viper.GetString("api.url")
	apiKey := viper.GetString("api.key")
	siteID := viper.GetString("cli.site_id")
	outputDir := viper.GetString("cli.output")

	// Auto-derive site_id for demo paths or validate for production
	if strings.Contains(inputPath, "/demos/") || strings.Contains(inputPath, "./demos/") {
		// Auto-derive site_id from demo path
		siteID = content.DeriveOrValidateSiteID(inputPath, siteID)
	} else {
		// Validate site_id for non-demo paths
		if siteID == "" || siteID == "demo" {
			log.Fatalf(`❌ site_id must be explicitly configured for non-demo sites.

💡 Examples:
   # Set via command line:
   insertr enhance --site-id mysite /path/to/site

   # Set in insertr.yaml:
   cli:
     site_id: "mysite"

   # Set via environment:
   INSERTR_CLI_SITE_ID=mysite insertr enhance /path/to/site

🚀 For demo sites under demos/, site_id is auto-derived from the directory name.`)
		}
	}

	// Create content client
	var client engine.ContentClient
	if apiURL != "" {
		fmt.Printf("🌐 Using content API: %s\n", apiURL)
		client = content.NewHTTPClient(apiURL, apiKey)
	} else if dbPath != "" {
		fmt.Printf("🗄️ Using database: %s\n", dbPath)
		database, err := db.NewDatabase(dbPath)
		if err != nil {
			log.Fatalf("Failed to initialize database: %v", err)
		}
		defer database.Close()
		client = engine.NewDatabaseClient(database)
	} else {
		fmt.Printf("🧪 No database or API configured, using mock content\n")
		client = content.NewMockClient()
	}

	// Load site-specific configuration
	enhancementConfig := content.EnhancementConfig{
		Discovery: content.DiscoveryConfig{
			Enabled:    false, // Default: disabled for explicit class="insertr" markings only
			Aggressive: false,
			Containers: true,
			Individual: true,
		},
		ContentInjection: true,
		GenerateIDs:      true,
	}

	// Override with site-specific discovery config if available
	if siteConfigs := viper.Get("server.sites"); siteConfigs != nil {
		if configs, ok := siteConfigs.([]interface{}); ok {
			for _, configInterface := range configs {
				if configMap, ok := configInterface.(map[string]interface{}); ok {
					if configSiteID, ok := configMap["site_id"].(string); ok && configSiteID == siteID {
						// Found matching site config, load discovery settings
						if discoveryMap, ok := configMap["discovery"].(map[string]interface{}); ok {
							if enabled, ok := discoveryMap["enabled"].(bool); ok {
								enhancementConfig.Discovery.Enabled = enabled
								fmt.Printf("🔧 Site '%s': discovery.enabled=%v\n", siteID, enabled)
							}
							if aggressive, ok := discoveryMap["aggressive"].(bool); ok {
								enhancementConfig.Discovery.Aggressive = aggressive
							}
							if containers, ok := discoveryMap["containers"].(bool); ok {
								enhancementConfig.Discovery.Containers = containers
							}
							if individual, ok := discoveryMap["individual"].(bool); ok {
								enhancementConfig.Discovery.Individual = individual
							}
						}
						break
					}
				}
			}
		}
	}

	// Create enhancer with loaded configuration
	enhancer := content.NewEnhancer(client, siteID, enhancementConfig)

	fmt.Printf("🚀 Starting enhancement process...\n")
	fmt.Printf("📁 Input: %s\n", inputPath)
	fmt.Printf("📁 Output: %s\n", outputDir)
	fmt.Printf("🏷️  Site ID: %s\n\n", siteID)

	// Enhance based on input type
	if isFile {
		// For single files, determine the output file path
		outputFilePath := outputDir
		if stat, err := os.Stat(outputDir); err == nil && stat.IsDir() {
			// Output is a directory, use input filename in output directory
			outputFilePath = filepath.Join(outputDir, filepath.Base(inputPath))
		}
		// If output doesn't exist or is a file, use it as-is as the output file path

		if err := enhancer.EnhanceFile(inputPath, outputFilePath); err != nil {
			log.Fatalf("Enhancement failed: %v", err)
		}
	} else {
		if err := enhancer.EnhanceDirectory(inputPath, outputDir); err != nil {
			log.Fatalf("Enhancement failed: %v", err)
		}
	}

	fmt.Printf("\n✅ Enhancement complete! Enhanced files available in: %s\n", outputDir)
}
