#!/usr/bin/env nu

# VAPORA Kubernetes Deployment Script
# Deploys VAPORA v2.0 to Kubernetes cluster

def main [
    --namespace: string = "vapora"  # Kubernetes namespace
    --registry: string = "docker.io"  # Docker registry
    --skip-secrets  # Skip secrets creation (if already exists)
    --dry-run  # Perform dry run without actual deployment
] {
    print $"(ansi green)🚀 VAPORA K8s Deployment Script(ansi reset)"
    print $"(ansi blue)═══════════════════════════════════════════════(ansi reset)"
    print $"Namespace: ($namespace)"
    print $"Registry:  ($registry)"
    print ""

    # Check prerequisites
    print $"(ansi yellow)📋 Checking prerequisites...(ansi reset)"
    check_prerequisites

    # Create namespace
    print ""
    print $"(ansi yellow)📦 Creating namespace...(ansi reset)"
    if $dry_run {
        kubectl create namespace $namespace --dry-run=client -o yaml
    } else {
        kubectl create namespace $namespace --dry-run=client -o yaml | kubectl apply -f -
    }

    # Create secrets (if not skipped)
    if not $skip_secrets {
        print ""
        print $"(ansi yellow)🔐 Creating secrets...(ansi reset)"
        print $"(ansi red)⚠️  WARNING: Update secrets in kubernetes/03-secrets.yaml before production deployment!(ansi reset)"

        if $dry_run {
            kubectl apply -f kubernetes/03-secrets.yaml --dry-run=client
        } else {
            kubectl apply -f kubernetes/03-secrets.yaml
        }
    }

    # Apply manifests in order
    print ""
    print $"(ansi yellow)📝 Applying Kubernetes manifests...(ansi reset)"

    let manifests = [
        "kubernetes/00-namespace.yaml"
        "kubernetes/01-surrealdb.yaml"
        "kubernetes/02-nats.yaml"
        "kubernetes/04-backend.yaml"
        "kubernetes/05-frontend.yaml"
        "kubernetes/06-agents.yaml"
        "kubernetes/07-mcp-server.yaml"
        "kubernetes/08-ingress.yaml"
    ]

    for manifest in $manifests {
        print $"  (ansi cyan)Applying ($manifest)...(ansi reset)"
        if $dry_run {
            kubectl apply -f $manifest --dry-run=client
        } else {
            kubectl apply -f $manifest
        }
    }

    if not $dry_run {
        # Wait for rollout
        print ""
        print $"(ansi yellow)⏳ Waiting for deployments to be ready...(ansi reset)"

        try {
            kubectl rollout status deployment/vapora-backend -n $namespace --timeout=5m
            kubectl rollout status deployment/vapora-frontend -n $namespace --timeout=5m
            kubectl rollout status deployment/vapora-agents -n $namespace --timeout=5m
            kubectl rollout status deployment/vapora-mcp-server -n $namespace --timeout=5m
        } catch {
            print $"(ansi red)❌ Timeout waiting for deployments. Check status manually.(ansi reset)"
        }

        # Get status
        print ""
        print $"(ansi yellow)📊 Deployment status:(ansi reset)"
        kubectl get all -n $namespace

        print ""
        print $"(ansi yellow)🌐 Ingress endpoints:(ansi reset)"
        kubectl get ingress -n $namespace

        print ""
        print $"(ansi green)✅ Deployment complete!(ansi reset)"
        print ""
        print $"(ansi cyan)Next steps:(ansi reset)"
        print "  1. Update ingress hostname in kubernetes/08-ingress.yaml"
        print "  2. Configure DNS to point to ingress IP"
        print "  3. Access UI at configured domain"
        print "  4. Monitor logs: kubectl logs -n vapora -l app=vapora-backend"
    } else {
        print ""
        print $"(ansi green)✅ Dry run complete! No changes were made.(ansi reset)"
    }
}

# Check if required tools are installed
def check_prerequisites [] {
    let required_tools = ["kubectl"]

    for tool in $required_tools {
        if (which $tool | is-empty) {
            print $"(ansi red)❌ Error: ($tool) is not installed(ansi reset)"
            exit 1
        }
    }

    # Check kubectl cluster connection
    try {
        kubectl cluster-info | ignore
        print $"(ansi green)✅ kubectl configured and connected(ansi reset)"
    } catch {
        print $"(ansi red)❌ Error: kubectl not configured or cluster not accessible(ansi reset)"
        exit 1
    }

    # Check if kubernetes manifests exist
    if not ("kubernetes" | path exists) {
        print $"(ansi red)❌ Error: kubernetes/ directory not found(ansi reset)"
        exit 1
    }
}
