#!/usr/bin/env nu

# Dashboard Management Commands
# Interactive dashboards and data visualization

use ../dashboard/marimo_integration.nu *

# Main dashboard command
export def main [
    subcommand?: string
    ...args: string
] {

    if ($subcommand | is-empty) {
        print "📊 Systems Provisioning Dashboard"
        print ""
        print "Interactive dashboards for infrastructure monitoring and analytics"
        print ""
        print "Usage: provisioning dashboard <subcommand> [args...]"
        print ""
        print "Subcommands:"
        print "  create [template] [name]  - Create interactive dashboard"
        print "  start <name> [port]       - Start dashboard server"
        print "  list                      - List available dashboards"
        print "  export <name> [output]    - Export dashboard to HTML"
        print "  demo                      - Create and start demo dashboard"
        print "  status                    - Show dashboard system status"
        print ""
        print "Templates:"
        print "  monitoring     - Real-time logs and metrics"
        print "  infrastructure - Server and cluster overview"
        print "  full          - Complete observability dashboard"
        print "  ai-insights   - AI-powered analytics and predictions"
        print ""
        print "Examples:"
        print "  provisioning dashboard demo"
        print "  provisioning dashboard create monitoring my-dashboard"
        print "  provisioning dashboard start my-dashboard 8080"
        print ""
        return
    }

    match $subcommand {
        "create" => {
            marimo_integration create ...$args
        }
        "start" => {
            marimo_integration start ...$args
        }
        "list" => {
            marimo_integration list
        }
        "export" => {
            marimo_integration export ...$args
        }
        "demo" => {
            create_demo_dashboard
        }
        "status" => {
            show_dashboard_status
        }
        _ => {
            print $"❌ Unknown subcommand: ($subcommand)"
            print "Run 'provisioning dashboard' for help"
        }
    }
}

# Create and start a demo dashboard
def create_demo_dashboard [] {
    print "🚀 Creating demo dashboard with live data..."

    # Check if API server is running
    let api_status = check_api_server_status

    if not $api_status {
        print "⚠️ API server not running. Starting API server..."
        start_api_server --port 3000 --background
        sleep 3sec
    }

    # Create AI insights dashboard
    marimo_integration create ai-insights demo-dashboard

    print ""
    print "🎉 Demo dashboard created and started!"
    print "📊 Open your browser to: http://localhost:8080"
    print ""
    print "Features available:"
    print "  🔍 Real-time log analysis"
    print "  📈 System metrics visualization"
    print "  🏗️ Infrastructure topology"
    print "  🤖 AI-powered insights and predictions"
    print "  📊 Interactive charts and tables"
    print ""
}

# Check API server status
def check_api_server_status [] {
    let response = (try {
        http get --allow-errors --full "http://localhost:3000/health"
    } catch {
        return false
    })
    ($response.status == 200) and ($response.body | get -o status | default "" | str trim) == "healthy"
}

# Start API server in background
def start_api_server [--port: int = 3000, --background = false] {
    if $background {
        nu -c "use ../api/server.nu *; start_api_server --port $port" &
    } else {
        use ../api/server.nu *
        start_api_server --port $port
    }
}

# Show dashboard system status
def show_dashboard_status [] {
    print "📊 Dashboard System Status"
    print ""

    # Check Marimo installation
    let marimo_available = check_marimo_available
    let marimo_status = if $marimo_available { "✅ Installed" } else { "❌ Not installed" }
    print $"Marimo: ($marimo_status)"

    # Check API server
    let api_status = check_api_server_status
    let api_display = if $api_status { "✅ Running" } else { "❌ Stopped" }
    print $"API Server: ($api_display)"

    # List dashboards
    let dashboards = list_dashboards
    print $"Dashboards: ($dashboards | length) available"

    if ($dashboards | length) > 0 {
        print ""
        print "Available dashboards:"
        $dashboards | select name modified | table
    }

    # System resources
    print ""
    print "System Resources:"
    let mem_info = (sys mem)
    print $"Memory: ($mem_info.used | into string) / ($mem_info.total | into string) used"

    print ""
    print "Quick start:"
    if not $marimo_available {
        print "1. Install Marimo: provisioning dashboard create install"
    }
    if not $api_status {
        print "2. Start API: provisioning api start"
    }
    print "3. Create dashboard: provisioning dashboard demo"
}
