#!/usr/bin/env nu
# Native execution script for Provisioning Platform services
# Run services directly on macOS without Docker

const PLATFORM_ROOT = "/Users/Akasha/project-provisioning/provisioning/platform"

# Service configuration
const SERVICES = {
    orchestrator: {
        name: "Orchestrator"
        port: 8080
        build_path: "orchestrator"
        binary: "provisioning-orchestrator"
        log_file: "~/.provisioning-platform/logs/orchestrator.log"
    }
    control_center: {
        name: "Control Center"
        port: 8081
        build_path: "control-center"
        binary: "control-center"
        log_file: "~/.provisioning-platform/logs/control-center.log"
    }
}

# Build all services
def "main build" [] {
    print $"🔨 Building all services from ($PLATFORM_ROOT)...\n"

    cd $PLATFORM_ROOT

    # Build workspace
    print "📦 Building Rust workspace (all services)..."
    cargo build --release

    if $env.LAST_EXIT_CODE != 0 {
        print "❌ Build failed!"
        return
    }

    print "\n✅ All services built successfully!"
    print $"   Binaries: ($PLATFORM_ROOT)/target/release/\n"
}

# Start a specific service
def "main start" [
    service: string  # Service name (orchestrator, control_center)
    --background (-b)  # Run in background
] {
    let service_config = ($SERVICES | get $service)

    print $"🚀 Starting ($service_config.name)..."

    # Ensure binary exists
    let binary_path = $"($PLATFORM_ROOT)/target/release/($service_config.binary)"

    if not ($binary_path | path exists) {
        print $"❌ Binary not found: ($binary_path)"
        print "   Run 'nu run-native.nu build' first"
        return
    }

    # Create log directory
    let log_dir = ($service_config.log_file | path dirname | path expand)
    mkdir $log_dir

    # Set environment variables
    $env.RUST_LOG = "info"
    $env.DATA_DIR = $"~/.provisioning-platform/data/($service)" | path expand

    # Create data directory
    mkdir $env.DATA_DIR

    if $background {
        # Background execution
        print $"   Running in background [logs: ($service_config.log_file)]"

        ^$binary_path out> ($service_config.log_file | path expand) err> ($service_config.log_file | path expand) &

        print $"   Service started on port ($service_config.port)"
        print $"   Check logs: tail -f ($service_config.log_file | path expand)"
    } else {
        # Foreground execution
        print $"   Running in foreground (Ctrl+C to stop)"
        print $"   Port: ($service_config.port)\n"

        ^$binary_path
    }
}

# Start all services
def "main start-all" [
    --background (-b)  # Run in background
] {
    print "🚀 Starting all services...\n"

    # Start orchestrator first (dependency)
    main start orchestrator --background
    sleep 2sec

    # Start control-center
    main start control_center --background

    print "\n✅ All services started!"
    print "   Orchestrator: http://localhost:8080"
    print "   Control Center: http://localhost:8081\n"

    if not $background {
        print "Press Ctrl+C to stop all services"
        sleep 1000day  # Keep alive
    }
}

# Stop a specific service
def "main stop" [
    service: string  # Service name
] {
    let service_config = ($SERVICES | get $service)

    print $"🛑 Stopping ($service_config.name)..."

    # Find and kill process by binary name
    let pids = (ps | where name =~ $service_config.binary | get pid)

    if ($pids | is-empty) {
        print $"   No running ($service_config.name) found"
    } else {
        $pids | each {|pid|
            kill -9 $pid
            print $"   Stopped process ($pid)"
        }
        print $"✅ ($service_config.name) stopped"
    }
}

# Stop all services
def "main stop-all" [] {
    print "🛑 Stopping all services...\n"

    main stop control_center
    main stop orchestrator

    print "\n✅ All services stopped!"
}

# Show status of services
def "main status" [] {
    print "📊 Service Status:\n"

    for service in ($SERVICES | columns) {
        let service_config = ($SERVICES | get $service)
        let pids = (ps | where name =~ $service_config.binary)

        if ($pids | is-empty) {
            print $"   ❌ ($service_config.name): Not running"
        } else {
            let pid = ($pids | first | get pid)
            print $"   ✅ ($service_config.name): Running \(PID: ($pid), Port: ($service_config.port)\)"
        }
    }

    print ""
}

# Show logs for a service
def "main logs" [
    service: string  # Service name
    --follow (-f)  # Follow log output
] {
    let service_config = ($SERVICES | get $service)
    let log_path = ($service_config.log_file | path expand)

    if not ($log_path | path exists) {
        print $"❌ No log file found: ($log_path)"
        return
    }

    if $follow {
        print $"📜 Following logs for ($service_config.name) \(Ctrl+C to stop\)...\n"
        tail -f $log_path
    } else {
        print $"📜 Latest logs for ($service_config.name):\n"
        tail -n 50 $log_path
    }
}

# Check health of services
def "main health" [] {
    print "🏥 Health Check:\n"

    # Check orchestrator
    try {
        let health = (http get http://localhost:8080/health)
        print $"   ✅ Orchestrator: Healthy"
    } catch {
        print $"   ❌ Orchestrator: Not responding"
    }

    # Check control-center
    try {
        let health = (http get http://localhost:8081/health)
        print $"   ✅ Control Center: Healthy"
    } catch {
        print $"   ❌ Control Center: Not responding"
    }

    print ""
}

# Show help
def "main help" [] {
    print "Provisioning Platform - Native Execution\n"
    print "Usage: nu run-native.nu <command> [options]\n"
    print "Commands:"
    print "  build              Build all services"
    print "  start <service>    Start a service (orchestrator|control_center)"
    print "  start-all          Start all services"
    print "  stop <service>     Stop a service"
    print "  stop-all           Stop all services"
    print "  status             Show service status"
    print "  logs <service>     Show service logs"
    print "  health             Check service health"
    print "  help               Show this help\n"
    print "Examples:"
    print "  nu run-native.nu build"
    print "  nu run-native.nu start orchestrator --background"
    print "  nu run-native.nu start-all"
    print "  nu run-native.nu logs orchestrator --follow"
    print "  nu run-native.nu stop-all\n"
}

# Main entry point
def main [] {
    main help
}
