# UI Management - Pages and Components
# Rustelo UI management commands for pages, components, and routes

# =============================================================================
# HELP
# =============================================================================

# Show all UI management options
h:
    @echo "🎨 UI Management - Pages & Components"
    @echo ""
    @echo "📄 PAGE MANAGEMENT:"
    @echo "  just ui pages-list           # List all generated page components"
    @echo "  just ui pages-info           # Detailed page component information"
    @echo "  just ui pages-rebuild        # Force rebuild all page components"
    @echo "  just ui pages-cache          # Show page cache status"
    @echo ""
    @echo "🧩 COMPONENT MANAGEMENT:"
    @echo "  just ui components-list      # List available components"
    @echo "  just ui components-foundation # List foundation components"
    @echo "  just ui components-local     # List local components"
    @echo ""
    @echo "🛣️  ROUTES MANAGEMENT:"
    @echo "  just ui routes-list          # List all configured routes"
    @echo "  just ui routes-by-lang       # Show routes by language"
    @echo "  just ui routes-enabled       # Show only enabled routes"
    @echo "  just ui routes-info <route>  # Detailed info for specific route"
    @echo "  just ui routes-validate      # Validate all route configurations"
    @echo ""
    @echo "🔧 DEVELOPMENT TOOLS:"
    @echo "  just ui check-generated      # Check all generated code"
    @echo "  just ui debug-level <0-2>    # Set debug level (0=off, 1=basic, 2=verbose)"
    @echo "  just ui foundation-discover  # Discover available foundation components"
    @echo "  just ui build-with-debug     # Build with debug output"
    @echo ""
    @echo "Example usage:"
    @echo "  just ui h                    # Show this help"
    @echo "  just ui routes-list          # List all routes"
    @echo "  just ui debug-level 2        # Enable verbose debug output"

# =============================================================================
# PAGE MANAGEMENT
# =============================================================================

# List all generated page components
pages-list:
    @echo "📄 Generated Page Components:"
    @echo ""
    @if [ -d "target/rustelo-cache/pages" ]; then \
        ls -la target/rustelo-cache/pages/page_*.rs 2>/dev/null | \
        awk '{printf "  %-25s %s %s %s\n", $9, $6, $7, $8}' | \
        sed 's|target/rustelo-cache/pages/page_||g' | \
        sed 's|\.rs||g' || echo "  No generated pages found"; \
    else \
        echo "  ❌ Cache directory not found. Run 'just build' first."; \
    fi
    @echo ""
    @echo "📊 Summary:"
    @find target/rustelo-cache/pages -name "page_*.rs" 2>/dev/null | wc -l | xargs printf "  Total generated pages: %d\n"

# Show detailed page component information
pages-info:
    @echo "📄 Detailed Page Component Information:"
    @echo ""
    @bash scripts/dev/check-generated.sh

# Force rebuild all page components
pages-rebuild:
    @echo "🔄 Rebuilding all page components..."
    @cargo clean -p website-pages
    @cargo build --package website-pages
    @echo "✅ Page components rebuilt successfully"

# Show page cache status
pages-cache:
    @echo "💾 Page Cache Status:"
    @echo ""
    @echo "📂 Cache locations:"
    @echo "  - Generated components: target/rustelo-cache/pages/"
    @echo "  - Build output: target/debug/build/website-pages-*/out/"
    @echo ""
    @if [ -d "target/rustelo-cache/pages" ]; then \
        echo "📊 Cache contents:"; \
        find target/rustelo-cache/pages -name "*.rs" -printf "  - %f (%TY-%Tm-%Td %TH:%TM)\n" 2>/dev/null | sort; \
    else \
        echo "❌ No cache found. Run 'just build' first."; \
    fi

# =============================================================================
# COMPONENT MANAGEMENT
# =============================================================================

# List available components
components-list:
    @echo "🧩 Available Components:"
    @echo ""
    @echo "🏗️  Foundation Components:"
    @cargo rustelo fn list -f component 2>/dev/null | head -20 || echo "  Run 'cargo build' first to see components"
    @echo ""
    @echo "📁 Local Components:"
    @find crates/components/src -name "*.rs" -not -name "mod.rs" -not -name "lib.rs" 2>/dev/null | \
     sed 's|.*/||g' | sed 's|\.rs||g' | sort | sed 's/^/  - /' || echo "  No local components found"

# List foundation components
components-foundation:
    @echo "🏗️  Foundation Components Discovery:"
    @echo ""
    @cargo rustelo fn list -f component --format table 2>/dev/null || echo "❌ Foundation discovery failed. Check rustelo CLI setup."

# List local components
components-local:
    @echo "📁 Local Components:"
    @echo ""
    @find crates -name "*.rs" -path "*/components/*" -not -name "mod.rs" -not -name "lib.rs" | \
     while read file; do \
       component=$(basename "$file" .rs); \
       echo "  - $component ($(dirname "$file"))"; \
     done

# =============================================================================
# ROUTES MANAGEMENT (with nushell commands)
# =============================================================================

# List all configured routes
[no-cd]
routes-list:
    #!/usr/bin/env bash
    echo "🛣️  All Configured Routes:"
    echo ""

    for file in site/config/routes/*.toml; do
        if [ -f "$file" ]; then
            lang=$(basename "$file" .toml)
            echo "📁 $lang.toml routes"
            echo "  Use 'just ui routes-enabled' for detailed view"
            echo ""
        fi
    done

# Show routes by language
routes-by-lang:
    #!/usr/bin/env nu
    echo "🌐 Routes by Language:"
    echo ""

    let route_files = (ls site/config/routes/*.toml)

    for file in $route_files {
        let lang = ($file.name | path basename | str replace ".toml" "")
        let routes = (open $file.name | get routes? | default [])
        let enabled_count = ($routes | where enabled | length)
        let total_count = ($routes | length)

        echo $"🗣️  ($lang | str upcase) Language: ($enabled_count)/($total_count) enabled"

        let enabled_routes = ($routes | where enabled)
        for route in $enabled_routes {
            let component = ($route.component? | default "Unknown")
            let path_info = ($route.path? | default "/")
            echo $"  - ($component) -> ($path_info)"
        }
        echo ""
    }

# Show only enabled routes
routes-enabled:
    #!/usr/bin/env nu
    echo "✅ Enabled Routes Only:"
    echo ""

    let route_files = (ls site/config/routes/*.toml)

    for file in $route_files {
        let lang = ($file.name | path basename | str replace ".toml" "")
        let routes = (open $file.name | get routes? | default [])
        let enabled_routes = ($routes | where enabled)

        if ($enabled_routes | length) > 0 {
            echo $"📁 ($lang):"
            for route in $enabled_routes {
                let component = ($route.component? | default "Unknown")
                let path_info = ($route.path? | default "/")
                let unified = ($route.unified_component? | default $"Unified($component)Page")
                echo $"  🎯 ($component) -> ($path_info) (unified: ($unified))"
            }
            echo ""
        }
    }

# Get detailed info for specific route
routes-info route:
    #!/usr/bin/env nu
    let search_route = "{{route}}"
    echo $"🔍 Route Information for: ($search_route)"
    echo ""

    let route_files = (ls site/config/routes/*.toml)
    mut found = false

    for file in $route_files {
        let lang = ($file.name | path basename | str replace ".toml" "")
        let routes = (open $file.name | get routes? | default [])

        for route in $routes {
            let component = ($route.component? | default "")
            if ($component | str contains $search_route) {
                $found = true
                echo $"📍 Found in ($lang).toml:"
                echo $"  Component: ($route.component? | default 'Unknown')"
                echo $"  Path: ($route.path? | default '/')"
                echo $"  Enabled: ($route.enabled)"
                echo $"  Unified: ($route.unified_component? | default 'Auto-generated')"
                echo $"  Language: ($route.language? | default $lang)"
                let description = ($route.description? | default "")
                if $description != "" {
                    echo $"  Description: ($description)"
                }
                echo ""
            }
        }
    }

    if not $found {
        echo $"❌ Route '($search_route)' not found in any configuration file"
    }

# Validate all route configurations
routes-validate:
    #!/usr/bin/env nu
    echo "🔧 Validating Route Configurations:"
    echo ""

    let route_files = (ls site/config/routes/*.toml)
    mut errors = 0

    for file in $route_files {
        let lang = ($file.name | path basename | str replace ".toml" "")
        echo $"📄 Validating ($lang).toml..."

        try {
            let routes = (open $file.name | get routes? | default [])
            let enabled_routes = ($routes | where enabled)

            echo $"  ✅ Parsed successfully: ($routes | length) total, ($enabled_routes | length) enabled"

            # Check for required fields
            for route in $enabled_routes {
                let component = ($route.component? | default "")
                if $component == "" {
                    echo $"  ⚠️  Route missing component field"
                    $errors = ($errors + 1)
                }
            }

        } catch { |err|
            echo $"  ❌ Parse error: ($err.msg)"
            $errors = ($errors + 1)
        }
    }

    echo ""
    if $errors == 0 {
        echo "🎉 All route configurations are valid!"
    } else {
        echo $"❌ Found ($errors) configuration errors"
    }

# =============================================================================
# DEVELOPMENT TOOLS
# =============================================================================

# Check all generated code
check-generated:
    @echo "🔍 Checking All Generated Code:"
    @echo ""
    @bash scripts/dev/check-generated.sh

# Set debug level (0=off, 1=basic, 2=verbose)
debug-level level:
    #!/usr/bin/env nu
    let new_level = {{level}}

    # Validate level
    if $new_level not-in [0, 1, 2] {
        echo "❌ Invalid debug level. Use 0 (off), 1 (basic), or 2 (verbose)"
        exit 1
    }

    echo $"🔧 Setting debug level to ($new_level)..."

    # Update manifest file
    let manifest_content = (open rustelo.manifest.toml)
    let updated_manifest = ($manifest_content | upsert build.debug $new_level)
    $updated_manifest | to toml | save rustelo.manifest.toml

    let level_desc = match $new_level {
        0 => "off - minimal output"
        1 => "basic - essential info only"
        2 => "verbose - full debug information"
    }

    echo $"✅ Debug level set to ($new_level) (($level_desc))"
    echo ""
    echo "🔄 Rebuild to see changes:"
    echo "  cargo clean -p website-pages && cargo build"

# Discover available foundation components
foundation-discover:
    @echo "🏗️  Foundation Component Discovery:"
    @echo ""
    @cargo rustelo fn list --format table 2>/dev/null || echo "❌ Foundation discovery unavailable. Check rustelo CLI setup."

# Build with debug output
build-with-debug:
    @echo "🔨 Building with Debug Output:"
    @echo ""
    @cargo build --package website-pages
    @echo ""
    @echo "📊 Generated components available in target/rustelo-cache/pages/"
