#!/bin/bash
# resolve-blockers.sh
# Automated script to resolve all remaining blockers

set -euo pipefail

# Load environment variables
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
if [ -f "${SCRIPT_DIR}/../.env" ]; then
    set -a
    source <(grep -v '^#' "${SCRIPT_DIR}/../.env" | grep -v '^$' | sed 's/^/export /')
    set +a
fi

# Colors
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

PASSED=0
FAILED=0
SKIPPED=0

log() {
    echo -e "${GREEN}[✓]${NC} $1"
    ((PASSED++))
}

error() {
    echo -e "${RED}[✗]${NC} $1"
    ((FAILED++))
}

warn() {
    echo -e "${YELLOW}[!]${NC} $1"
    ((SKIPPED++))
}

info() {
    echo -e "${BLUE}[i]${NC} $1"
}

# Blocker 1: Kubernetes
setup_kubernetes() {
    info "=== Blocker 1: Kubernetes Cluster Setup ==="
    echo ""
    
    # Check kubectl
    if command -v kubectl &> /dev/null; then
        log "kubectl is installed"
    else
        warn "kubectl not installed - install manually: https://kubernetes.io/docs/tasks/tools/"
        return 1
    fi
    
    # Check for existing cluster
    if kubectl cluster-info &> /dev/null 2>&1; then
        log "Kubernetes cluster is accessible"
        kubectl get nodes 2>/dev/null && log "Cluster nodes are ready" || warn "Cluster accessible but nodes not ready"
        return 0
    fi
    
    # Check Docker for kind/minikube
    if ! docker info &> /dev/null; then
        warn "Docker is not running - required for kind/minikube"
        warn "Start Docker or use existing Kubernetes cluster"
        return 1
    fi
    
    # Try kind
    if command -v kind &> /dev/null; then
        info "kind is installed, creating cluster..."
        if kind create cluster --name sankofa 2>/dev/null; then
            log "kind cluster 'sankofa' created"
            kubectl config use-context kind-sankofa
            return 0
        else
            warn "Failed to create kind cluster (may already exist)"
            if kind get clusters | grep -q sankofa; then
                log "Cluster 'sankofa' already exists"
                kubectl config use-context kind-sankofa
                return 0
            fi
        fi
    else
        warn "kind not installed - install manually or use existing cluster"
    fi
    
    # Try minikube
    if command -v minikube &> /dev/null; then
        info "minikube is installed, starting cluster..."
        if minikube start --driver=docker 2>/dev/null; then
            log "minikube cluster started"
            return 0
        else
            warn "Failed to start minikube (may already be running)"
            if minikube status &> /dev/null; then
                log "minikube cluster is running"
                return 0
            fi
        fi
    fi
    
    warn "No Kubernetes cluster available - manual setup required"
    return 1
}

install_crossplane() {
    info "Installing Crossplane..."
    
    if ! kubectl cluster-info &> /dev/null 2>&1; then
        warn "No Kubernetes cluster - skipping Crossplane installation"
        return 1
    fi
    
    # Check if Crossplane is already installed
    if kubectl get namespace crossplane-system &> /dev/null 2>&1; then
        if kubectl get pods -n crossplane-system &> /dev/null 2>&1; then
            log "Crossplane is already installed"
            return 0
        fi
    fi
    
    # Check for helm
    if ! command -v helm &> /dev/null; then
        warn "helm not installed - install manually: https://helm.sh/docs/intro/install/"
        return 1
    fi
    
    # Install Crossplane
    if helm repo list | grep -q crossplane-stable; then
        log "Crossplane Helm repo already added"
    else
        helm repo add crossplane-stable https://charts.crossplane.io/stable
        helm repo update
        log "Crossplane Helm repo added"
    fi
    
    if helm list -n crossplane-system | grep -q crossplane; then
        log "Crossplane is already installed via Helm"
    else
        if helm install crossplane crossplane-stable/crossplane \
            --namespace crossplane-system \
            --create-namespace \
            --wait 2>/dev/null; then
            log "Crossplane installed successfully"
        else
            warn "Failed to install Crossplane - check logs"
            return 1
        fi
    fi
    
    # Verify
    sleep 5
    if kubectl get pods -n crossplane-system &> /dev/null; then
        log "Crossplane pods are running"
        kubectl get pods -n crossplane-system
    else
        warn "Crossplane pods not ready yet"
    fi
}

# Blocker 2: SSH
setup_ssh() {
    info "=== Blocker 2: SSH Access Setup ==="
    echo ""
    
    SSH_KEY="${SSH_KEY:-$HOME/.ssh/sankofa_proxmox}"
    
    # Generate key if not exists
    if [ ! -f "$SSH_KEY" ]; then
        info "Generating SSH key..."
        if ssh-keygen -t ed25519 -C "sankofa-proxmox" -f "$SSH_KEY" -N "" -q; then
            log "SSH key generated: $SSH_KEY"
        else
            error "Failed to generate SSH key"
            return 1
        fi
    else
        log "SSH key already exists: $SSH_KEY"
    fi
    
    # Test ML110-01
    info "Testing SSH to ML110-01..."
    if ssh -i "$SSH_KEY" -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@192.168.11.10 'echo "SSH working"' &> /dev/null; then
        log "SSH to ML110-01 works"
    else
        warn "SSH to ML110-01 failed - manual key copy required"
        info "Run: ssh-copy-id -i $SSH_KEY.pub root@192.168.11.10"
    fi
    
    # Test R630-01
    info "Testing SSH to R630-01..."
    if ssh -i "$SSH_KEY" -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@192.168.11.11 'echo "SSH working"' &> /dev/null; then
        log "SSH to R630-01 works"
    else
        warn "SSH to R630-01 failed - manual key copy required"
        info "Run: ssh-copy-id -i $SSH_KEY.pub root@192.168.11.11"
    fi
}

# Blocker 3: Images
verify_images() {
    info "=== Blocker 3: Image Verification ==="
    echo ""
    
    SSH_KEY="${SSH_KEY:-$HOME/.ssh/sankofa_proxmox}"
    
    # Check ML110-01
    info "Checking images on ML110-01..."
    if ssh -i "$SSH_KEY" -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@192.168.11.10 'pveam list local 2>/dev/null | grep -i ubuntu' &> /dev/null; then
        local images=$(ssh -i "$SSH_KEY" -o StrictHostKeyChecking=no root@192.168.11.10 'pveam list local 2>/dev/null | grep -i ubuntu' 2>/dev/null || echo "")
        if [ -n "$images" ]; then
            log "Images found on ML110-01:"
            echo "$images" | head -3 | sed 's/^/  /'
        else
            warn "No Ubuntu images found on ML110-01"
        fi
    else
        warn "Cannot check images on ML110-01 (SSH not configured)"
    fi
    
    # Check R630-01
    info "Checking images on R630-01..."
    if ssh -i "$SSH_KEY" -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@192.168.11.11 'pveam list local 2>/dev/null | grep -i ubuntu' &> /dev/null; then
        local images=$(ssh -i "$SSH_KEY" -o StrictHostKeyChecking=no root@192.168.11.11 'pveam list local 2>/dev/null | grep -i ubuntu' 2>/dev/null || echo "")
        if [ -n "$images" ]; then
            log "Images found on R630-01:"
            echo "$images" | head -3 | sed 's/^/  /'
        else
            warn "No Ubuntu images found on R630-01"
        fi
    else
        warn "Cannot check images on R630-01 (SSH not configured)"
    fi
}

main() {
    echo ""
    echo "╔══════════════════════════════════════════════════════════════╗"
    echo "║          Resolving All Remaining Blockers                   ║"
    echo "╚══════════════════════════════════════════════════════════════╝"
    echo ""
    echo "Priority Order:"
    echo "  1. SSH Access (needed for image verification)"
    echo "  2. Image Verification (needed before VM deployment)"
    echo "  3. Kubernetes Cluster (needed for provider deployment)"
    echo ""
    
    # Blocker 2: SSH (PRIORITY 1 - Do this first)
    setup_ssh
    echo ""
    
    # Blocker 3: Images (PRIORITY 2 - Depends on SSH)
    verify_images
    echo ""
    
    # Blocker 1: Kubernetes (PRIORITY 3 - Can be done in parallel)
    if setup_kubernetes; then
        install_crossplane
    fi
    echo ""
    
    # Summary
    echo "╔══════════════════════════════════════════════════════════════╗"
    echo "║                    Summary                                   ║"
    echo "╚══════════════════════════════════════════════════════════════╝"
    echo ""
    echo -e "${GREEN}Passed:${NC} ${PASSED}"
    echo -e "${YELLOW}Skipped/Warnings:${NC} ${SKIPPED}"
    echo -e "${RED}Failed:${NC} ${FAILED}"
    echo ""
    
    if [ $FAILED -eq 0 ]; then
        log "All automated steps completed!"
        if [ $SKIPPED -gt 0 ]; then
            warn "Some steps require manual intervention (see warnings above)"
        fi
    else
        error "Some steps failed - manual intervention required"
    fi
    echo ""
}

main "$@"

