#!/usr/bin/env nu
# Docker execution script for Provisioning Platform services
# Run services in Docker containers (OrbStack/Docker Desktop)

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

# Deployment modes and their compose files
const MODES = {
    solo: "infrastructure/docker/docker-compose.solo.yaml"
    multiuser: "infrastructure/docker/docker-compose.multi-user.yaml"
    cicd: "infrastructure/docker/docker-compose.cicd.yaml"
    enterprise: "infrastructure/docker/docker-compose.enterprise.yaml"
}

# Build all Docker images
def "main build" [
    mode: string = "solo"  # Deployment mode (solo, multiuser, cicd, enterprise)
    --no-cache  # Build without cache
] {
    print $"🔨 Building Docker images for ($mode) mode...\n"

    cd $PLATFORM_ROOT

    let compose_file = ($MODES | get $mode)

    let cache_flag = if $no_cache { "--no-cache" } else { "" }

    # Build images
    print "📦 Building images (this may take several minutes)...\n"

    docker-compose -f infrastructure/docker/docker-compose.yaml -f $compose_file build $cache_flag

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

    print "\n✅ All images built successfully!"
    print "\nBuilt images:"
    docker images | where name =~ "platform" | select name tag size created
}

# Start services
def "main start" [
    mode: string = "solo"  # Deployment mode
    --detach (-d)  # Run in background
    --build  # Build before starting
] {
    print $"🚀 Starting services in ($mode) mode...\n"

    cd $PLATFORM_ROOT

    let compose_file = ($MODES | get $mode)

    # Build if requested
    if $build {
        main build $mode
    }

    # Start services
    let detach_flag = if $detach { "-d" } else { "" }

    docker-compose -f infrastructure/docker/docker-compose.yaml -f $compose_file up $detach_flag

    if $detach {
        print "\n✅ Services started in background!"
        print "\n📊 Service URLs:"
        print "   Orchestrator:    http://localhost:8080"
        print "   Control Center:  http://localhost:8081"
        print "   KMS:             http://localhost:9998  (mandatory per ADR-007)"

        if $mode in ["enterprise"] {
            print "   Grafana:         http://localhost:3001"
            print "   Prometheus:      http://localhost:9090"
        }

        print "\n💡 Tips:"
        print "   Check status:  nu run-docker.nu status"
        print "   View logs:     nu run-docker.nu logs <service>"
        print "   Stop all:      nu run-docker.nu stop"
    }
}

# Stop services
def "main stop" [
    --volumes (-v)  # Remove volumes (deletes data!)
] {
    print "🛑 Stopping all services...\n"

    cd $PLATFORM_ROOT

    let vol_flag = if $volumes { "--volumes" } else { "" }

    docker-compose down $vol_flag

    print "\n✅ All services stopped!"

    if $volumes {
        print "⚠️  All data volumes removed!"
    }
}

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

    cd $PLATFORM_ROOT

    let containers = (docker ps --filter "name=provisioning-" --format json | lines | each {|line| $line | from json})

    if ($containers | is-empty) {
        print "   No services running\n"
        print "💡 Start services: nu run-docker.nu start [mode]"
        return
    }

    for container in $containers {
        let name = ($container.Names)
        let status = ($container.Status)
        let ports = ($container.Ports)

        print $"   ✅ ($name)"
        print $"      Status: ($status)"
        if not ($ports | is-empty) {
            print $"      Ports:  ($ports)"
        }
    }

    print ""
}

# Show logs for a service
def "main logs" [
    service: string  # Service name (orchestrator, control-center, etc.)
    --follow (-f)  # Follow log output
    --tail (-n): int = 50  # Number of lines to show
] {
    cd $PLATFORM_ROOT

    let container_name = $"provisioning-($service)"

    let follow_flag = if $follow { "-f" } else { "" }

    print $"📜 Logs for ($service):\n"

    docker logs --tail $tail $follow_flag $container_name
}

# Execute command in service container
def "main exec" [
    service: string  # Service name
    ...command: string  # Command to execute
] {
    cd $PLATFORM_ROOT

    let container_name = $"provisioning-($service)"

    docker exec -it $container_name ...$command
}

# Show resource usage
def "main stats" [] {
    print "📈 Resource Usage:\n"

    docker stats --no-stream --filter "name=provisioning-" --format "table {{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}\t{{.NetIO}}"

    print ""
}

# Health check
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"
    }

    # Check KMS (mandatory per ADR-007)
    try {
        let health = (http get http://localhost:9998/health)
        print $"   ✅ KMS: Healthy"
    } catch {
        print $"   ❌ KMS: Not responding (required per ADR-007)"
    }

    print ""
}

# Restart services
def "main restart" [
    mode: string = "solo"  # Deployment mode
] {
    print "🔄 Restarting services...\n"

    main stop
    sleep 2sec
    main start $mode --detach

    print "\n✅ Services restarted!"
}

# Clean up everything (containers, images, volumes)
def "main clean" [
    --all  # Remove images too
] {
    print "🧹 Cleaning up Docker resources...\n"

    cd $PLATFORM_ROOT

    # Stop and remove containers and volumes
    docker-compose down --volumes

    if $all {
        print "   Removing images..."
        docker images | where name =~ "platform-" | each {|img|
            docker rmi -f $img.id
        }
        print "✅ All resources cleaned!"
    } else {
        print "✅ Containers and volumes cleaned!"
        print "💡 Remove images too: nu run-docker.nu clean --all"
    }
}

# Show Docker compose config
def "main config" [
    mode: string = "solo"  # Deployment mode
] {
    cd $PLATFORM_ROOT

    let compose_file = ($MODES | get $mode)

    docker-compose -f docker-compose.yaml -f $compose_file config
}

# Show help
def "main help" [] {
    print "Provisioning Platform - Docker Execution\n"
    print "Usage: nu run-docker.nu <command> [options]\n"
    print "Commands:"
    print "  build [mode]       Build Docker images (solo|multiuser|cicd|enterprise)"
    print "  start [mode]       Start services"
    print "  stop               Stop all services"
    print "  restart [mode]     Restart services"
    print "  status             Show service status"
    print "  logs <service>     Show service logs"
    print "  exec <service>     Execute command in container"
    print "  stats              Show resource usage"
    print "  health             Check service health"
    print "  config [mode]      Show docker-compose configuration"
    print "  clean              Clean up containers and volumes"
    print "  help               Show this help\n"
    print "Deployment Modes:"
    print "  solo        - Minimal setup (2 CPU, 4GB RAM) + KMS"
    print "  multiuser   - Team collaboration (4 CPU, 8GB RAM) + KMS"
    print "  cicd        - CI/CD pipelines (8 CPU, 16GB RAM) + KMS"
    print "  enterprise  - Full stack with KMS + monitoring (16 CPU, 32GB RAM)\n"
    print "Note: KMS is mandatory in all modes per ADR-007\n"
    print "Examples:"
    print "  nu run-docker.nu build solo"
    print "  nu run-docker.nu start solo --detach"
    print "  nu run-docker.nu logs orchestrator --follow"
    print "  nu run-docker.nu exec orchestrator bash"
    print "  nu run-docker.nu stop\n"
}

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