package cmd

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

	"github.com/spf13/cobra"
)

var demoCmd = &cobra.Command{
	Use:   "demo",
	Short: "Run a demonstration of Devour features",
	Long: `Demonstrates Devour's capabilities by scraping sample documentation
and showing the enhanced markdown output.

This command will:
1. Scrape Go's HTTP package documentation
2. Generate enhanced markdown output
3. Display a preview of the results
4. Show statistics about the operation`,
	RunE: runDemo,
}

func init() {
}

func runDemo(cmd *cobra.Command, args []string) error {
	fmt.Println("🎬 Devour Feature Demonstration")
	fmt.Println("═══════════════════════════════════════════════════════════════")
	fmt.Println()

	// Create demo directory
	demoDir := "devour_demo"
	if err := os.MkdirAll(demoDir, 0755); err != nil {
		return fmt.Errorf("failed to create demo directory: %w", err)
	}

	fmt.Println("📍 Step 1: Scraping Go HTTP package documentation...")
	fmt.Println("   Command: devour get go http --format markdown --output devour_demo")
	fmt.Println()

	// Set demo output directory and format
	scrapeOutput = demoDir
	scrapeFormat = "markdown"

	// Use the get command logic to fetch Go HTTP docs
	err := runGet(cmd, []string{"go", "http"})
	if err != nil {
		return fmt.Errorf("demo scrape failed: %w", err)
	}

	fmt.Println()
	fmt.Println("📊 Step 2: Analyzing results...")

	// Count files in demo directory
	files, err := os.ReadDir(demoDir)
	if err != nil {
		return fmt.Errorf("failed to read demo directory: %w", err)
	}

	fmt.Printf("   ✓ Generated %d markdown files\n", len(files))

	// Show file sizes
	var totalSize int64
	for _, file := range files {
		if !file.IsDir() {
			info, err := file.Info()
			if err == nil {
				totalSize += info.Size()
			}
		}
	}
	fmt.Printf("   ✓ Total size: %d bytes\n", totalSize)

	fmt.Println()
	fmt.Println("📖 Step 3: Preview of enhanced markdown output...")

	// Find and show preview of first markdown file
	var firstFile string
	for _, file := range files {
		if !file.IsDir() && filepath.Ext(file.Name()) == ".md" {
			firstFile = filepath.Join(demoDir, file.Name())
			break
		}
	}

	if firstFile != "" {
		content, err := os.ReadFile(firstFile)
		if err == nil {
			// Show first 20 lines
			lines := strings.Split(string(content), "\n")
			fmt.Printf("   From file: %s\n", filepath.Base(firstFile))
			fmt.Println("   ─────────────────────────────────────────")
			for i, line := range lines {
				if i >= 20 {
					fmt.Printf("   ... (%d more lines)\n", len(lines)-20)
					break
				}
				fmt.Printf("   %s\n", line)
			}
		}
	}

	fmt.Println()
	fmt.Println("✨ Demo Complete!")
	fmt.Println()
	fmt.Println("🚀 What you can do next:")
	fmt.Printf("   • View all files: ls -la %s/\n", demoDir)
	fmt.Printf("   • Open in editor: code %s/\n", demoDir)
	fmt.Println("   • Try other languages: devour get python asyncio")
	fmt.Println("   • Use enhanced format: devour get react hooks --format markdown")
	fmt.Println("   • See all languages: devour languages")
	fmt.Println()
	fmt.Println("💡 Pro Tip: The enhanced markdown includes:")
	fmt.Println("   • 📋 Document metadata tables")
	fmt.Println("   • 📑 Auto-generated table of contents")
	fmt.Println("   • 🎨 Visual indicators for important content")
	fmt.Println("   • 🔗 Automatic link conversion")
	fmt.Println("   • 📚 Structured content sections")

	return nil
}
