package cmd

import (
	"fmt"
	"os"

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

var (
	autoEnhanceOutput     string
	autoEnhanceAggressive bool
)

var autoEnhanceCmd = &cobra.Command{
	Use:   "auto-enhance [input-dir]",
	Short: "Automatically detect and add insertr classes to HTML elements",
	Long: `Auto-enhance scans HTML files and automatically adds insertr classes to viable content elements.

This command uses intelligent heuristics to detect editable content:
- Text-only elements (headers, paragraphs, simple links)
- Elements with safe inline formatting (strong, em, span, etc.)  
- Container elements that benefit from expansion
- Buttons and other interactive content elements

Examples:
  insertr auto-enhance ./site --output ./enhanced
  insertr auto-enhance ./blog --output ./blog-enhanced --aggressive
  insertr auto-enhance /path/to/site --output /path/to/enhanced`,
	Args: cobra.ExactArgs(1),
	RunE: runAutoEnhance,
}

func runAutoEnhance(cmd *cobra.Command, args []string) error {
	inputDir := args[0]

	// Validate input directory
	if _, err := os.Stat(inputDir); os.IsNotExist(err) {
		return fmt.Errorf("input directory does not exist: %s", inputDir)
	}

	// Default output directory if not specified
	if autoEnhanceOutput == "" {
		autoEnhanceOutput = inputDir + "-enhanced"
	}

	fmt.Printf("🔍 Auto-enhancing HTML files...\n")
	fmt.Printf("📁 Input: %s\n", inputDir)
	fmt.Printf("📁 Output: %s\n", autoEnhanceOutput)
	if autoEnhanceAggressive {
		fmt.Printf("⚡ Aggressive mode: enabled\n")
	}
	fmt.Printf("\n")

	// Create auto enhancer
	enhancer := content.NewAutoEnhancer()

	// Run auto enhancement
	result, err := enhancer.EnhanceDirectory(inputDir, autoEnhanceOutput, autoEnhanceAggressive)
	if err != nil {
		return fmt.Errorf("auto-enhancement failed: %w", err)
	}

	// Print results
	fmt.Printf("✅ Auto-enhancement complete!\n\n")
	fmt.Printf("📊 Results:\n")
	fmt.Printf("   Files processed: %d\n", result.FilesProcessed)
	fmt.Printf("   Elements enhanced: %d\n", result.ElementsEnhanced)
	fmt.Printf("   Containers added: %d\n", result.ContainersAdded)
	fmt.Printf("   Individual elements: %d\n", result.IndividualsAdded)

	if len(result.SkippedFiles) > 0 {
		fmt.Printf("\n⚠️  Skipped files (%d):\n", len(result.SkippedFiles))
		for _, file := range result.SkippedFiles {
			fmt.Printf("   - %s\n", file)
		}
	}

	fmt.Printf("\n🎯 Enhanced files ready in: %s\n", autoEnhanceOutput)
	fmt.Printf("📝 Use 'insertr enhance %s' to inject content from database\n", autoEnhanceOutput)

	return nil
}

func init() {
	autoEnhanceCmd.Flags().StringVarP(&autoEnhanceOutput, "output", "o", "", "output directory for enhanced files")
	autoEnhanceCmd.Flags().BoolVar(&autoEnhanceAggressive, "aggressive", false, "aggressive mode: enhance single-child containers")

	rootCmd.AddCommand(autoEnhanceCmd)
}
