# =============================================================================
# RUSTELO TOOLS MODULE
# Unified development toolkit for analysis, generation, and publishing
# =============================================================================

# Set shell for all commands in this module
set shell := ["bash", "-c"]

# Tools binary path
TOOLS_BIN := "cargo run --package tools --bin tools --features cli"

# =============================================================================
# ANALYSIS & DOCUMENTATION
# =============================================================================

# Generate comprehensive project analysis and documentation
tools-analyze format="markdown" output="site/info":
    @echo "🔍 Analyzing project structure..."
    {{TOOLS_BIN}} analyze --format {{format}} --output {{output}}
    @echo "✅ Analysis complete! Check {{output}}/"

# Generate documentation only (alias for analyze)
tools-docs: (tools-analyze "markdown" "site/info")

# Validate generated documentation
tools-validate:
    @echo "📋 Validating generated documentation..."
    @if [ -d "site/info" ]; then \
        echo "✅ Documentation directory exists"; \
        find site/info -name "*.md" -exec echo "  📄 {}" \;; \
        find site/info -name "*.json" -exec echo "  📊 {}" \;; \
    else \
        echo "❌ No documentation found. Run: just tools-analyze"; \
        exit 1; \
    fi

# Clean generated documentation
tools-clean:
    @echo "🧹 Cleaning generated documentation..."
    rm -rf site/info
    @echo "✅ Documentation cleaned"

# Refresh documentation (clean + generate)
tools-refresh: tools-clean tools-analyze

# =============================================================================
# CODE GENERATION
# =============================================================================

# Generate a new page
tools-generate-page name template="basic":
    @echo "🚀 Generating page: {{name}}"
    {{TOOLS_BIN}} generate page {{name}} --template {{template}}

# Generate a new component
tools-generate-component name template="basic":
    @echo "🧩 Generating component: {{name}}"
    {{TOOLS_BIN}} generate component {{name}} --template {{template}}

# Generate a new route
tools-generate-route path:
    @echo "🛣️ Generating route: {{path}}"
    {{TOOLS_BIN}} generate route {{path}}

# Generate a new template
tools-generate-template name:
    @echo "📄 Generating template: {{name}}"
    {{TOOLS_BIN}} generate template {{name}}

# List available templates
tools-list-templates:
    @echo "📋 Available templates:"
    @if [ -d "site/templates" ]; then \
        find site/templates -name "*.tera" -exec basename {} .tera \;; \
    else \
        echo "  No templates directory found"; \
    fi

# =============================================================================
# INTERACTIVE MANAGEMENT
# =============================================================================

# Launch interactive tools manager (TUI)
tools-manage mode="dashboard":
    @echo "🎛️ Launching Rustelo Tools Manager..."
    {{TOOLS_BIN}} manage --mode {{mode}}

# Quick page editor
tools-edit-page name:
    @echo "✏️ Editing page: {{name}}"
    {{TOOLS_BIN}} manage --mode editor --page {{name}}

# =============================================================================
# PUBLISHING & SYNC
# =============================================================================

# Sync with main Rustelo project
tools-sync target="templates":
    @echo "🔄 Syncing {{target}} with Rustelo project..."
    {{TOOLS_BIN}} publish sync {{target}}

# Package project for distribution
tools-package format="template" output="dist":
    @echo "📦 Packaging project ({{format}})..."
    {{TOOLS_BIN}} publish package --format {{format}} --output {{output}}

# Deploy documentation
tools-deploy target="github-pages":
    @echo "🚀 Deploying documentation to {{target}}..."
    {{TOOLS_BIN}} docs deploy {{target}}

# Serve documentation locally
tools-serve port="8080":
    @echo "🌐 Serving documentation on http://localhost:{{port}}"
    {{TOOLS_BIN}} docs serve --port {{port}}

# =============================================================================
# DEVELOPMENT WORKFLOW INTEGRATION
# =============================================================================

# Complete development setup with tools integration
tools-dev-complete:
    #!/usr/bin/env bash
    echo "🚀 Starting complete Rustelo development environment..."

    # Start main development server in background
    echo "  🌐 Starting development server..."
    just dev &
    DEV_PID=$!

    # Generate fresh documentation
    echo "  📚 Generating documentation..."
    just tools-analyze

    # Start documentation server
    echo "  📖 Starting documentation server..."
    just tools-serve 8081 &
    DOCS_PID=$!

    echo ""
    echo "✅ Development environment ready!"
    echo "  🌐 Main app: http://localhost:3030"
    echo "  📖 Documentation: http://localhost:8081"
    echo "  🎛️ Tools manager: just tools-manage"
    echo ""
    echo "Press Ctrl+C to stop all services..."

    # Trap Ctrl+C to cleanup
    trap 'echo "🛑 Shutting down..."; kill $DEV_PID $DOCS_PID 2>/dev/null; exit' INT

    # Wait for Ctrl+C
    wait

# Fast development with automatic tools refresh
tools-dev-watch:
    #!/usr/bin/env bash
    echo "👁️ Starting development with tools auto-refresh..."

    # Start development server
    just dev &
    DEV_PID=$!

    # Watch for changes and regenerate docs
    echo "  🔍 Watching for changes..."
    while true; do
        if command -v fswatch >/dev/null 2>&1; then
            fswatch -o src/ site/ | while read; do
                echo "  🔄 Changes detected, regenerating documentation..."
                just tools-analyze > /dev/null 2>&1
            done
        else
            echo "  ⚠️ fswatch not available, install with: brew install fswatch"
            echo "  📚 Generating documentation once..."
            just tools-analyze
            break
        fi
    done &
    WATCH_PID=$!

    trap 'echo "🛑 Shutting down..."; kill $DEV_PID $WATCH_PID 2>/dev/null; exit' INT
    wait

# Setup tools development environment
tools-setup:
    @echo "🔧 Setting up Rustelo Tools development environment..."
    @echo "  📦 Checking tools crate..."
    cargo check --package tools --features analysis-only
    @echo "  📁 Creating directories..."
    mkdir -p site/info site/templates dist
    @echo "  📋 Generating initial documentation..."
    just tools-analyze
    @echo "✅ Tools environment ready!"

# =============================================================================
# UTILITIES & DIAGNOSTICS
# =============================================================================

# Show tools status and capabilities
tools-status:
    @echo "🛠️ Rustelo Tools Status"
    @echo "========================"
    @echo ""
    @echo "📦 Crate Status:"
    @cargo check --package tools --quiet && echo "  ✅ Tools crate builds successfully" || echo "  ❌ Tools crate has build errors"
    @echo ""
    @echo "🎯 Available Features:"
    @echo "  📊 analysis-only (minimal build features)"
    @echo "  🎨 templates (Tera template system)"
    @echo "  🎛️ cli (interactive management)"
    @echo "  📡 publishing (sync & deployment)"
    @echo ""
    @echo "📁 Generated Content:"
    @if [ -d "site/info" ]; then \
        echo "  📚 Documentation: $(find site/info -name "*.md" | wc -l) markdown files"; \
        echo "  📊 Data files: $(find site/info -name "*.json" | wc -l) JSON files"; \
    else \
        echo "  📚 No documentation generated yet"; \
    fi
    @echo ""
    @echo "🚀 Quick Start:"
    @echo "  just tools-analyze     # Generate documentation"
    @echo "  just tools-manage      # Interactive manager"
    @echo "  just tools-dev-complete # Full development environment"

# Test all tools functionality
tools-test:
    @echo "🧪 Testing Rustelo Tools functionality..."
    @echo "  📊 Testing analysis..."
    just tools-analyze > /dev/null 2>&1 && echo "  ✅ Analysis works" || echo "  ❌ Analysis failed"
    @echo "  🏗️ Testing build..."
    cargo check --package tools --quiet && echo "  ✅ Build works" || echo "  ❌ Build failed"
    @echo "  📋 Testing documentation generation..."
    @[ -d "site/info" ] && echo "  ✅ Documentation generated" || echo "  ❌ No documentation found"

# Show available tools commands
tools-help:
    @echo "🛠️ Rustelo Tools Commands"
    @echo "=========================="
    @echo ""
    @echo "📊 Analysis & Documentation:"
    @echo "  tools-analyze          Generate project analysis"
    @echo "  tools-docs             Generate documentation (alias)"
    @echo "  tools-validate         Validate generated docs"
    @echo "  tools-refresh          Clean and regenerate docs"
    @echo "  tools-clean            Remove generated docs"
    @echo ""
    @echo "🚀 Code Generation:"
    @echo "  tools-generate-page    Create new page"
    @echo "  tools-generate-component Create new component"
    @echo "  tools-generate-route   Create new route"
    @echo "  tools-list-templates   Show available templates"
    @echo ""
    @echo "🎛️ Interactive Management:"
    @echo "  tools-manage           Launch TUI manager"
    @echo "  tools-edit-page        Quick page editor"
    @echo ""
    @echo "📡 Publishing & Sync:"
    @echo "  tools-sync             Sync with Rustelo project"
    @echo "  tools-package          Package for distribution"
    @echo "  tools-deploy           Deploy documentation"
    @echo "  tools-serve            Serve docs locally"
    @echo ""
    @echo "🔧 Development Workflow:"
    @echo "  tools-dev-complete     Complete dev environment"
    @echo "  tools-dev-watch        Dev with auto-refresh"
    @echo "  tools-setup            Setup tools environment"
    @echo ""
    @echo "🔍 Utilities:"
    @echo "  tools-status           Show tools status"
    @echo "  tools-test             Test functionality"
    @echo "  tools-help             Show this help"

# =============================================================================
# ALIASES FOR CONVENIENCE
# =============================================================================

# Short aliases for common commands
alias ta := tools-analyze
alias tm := tools-manage
alias tg := tools-generate-page
alias ts := tools-status
alias th := tools-help
