#!/bin/bash
# Dry Run: Deploy All VMs to r630-01
# Validates all VM configurations targeting r630-01 without actually deploying

set -o pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"

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

echo "=========================================="
echo "Dry Run: VM Deployment to r630-01"
echo "=========================================="
echo ""
echo -e "${CYAN}This is a DRY RUN - no VMs will be created${NC}"
echo ""

# Check if kubectl is available
if ! command -v kubectl &> /dev/null; then
    echo -e "${RED}Error: kubectl not found${NC}"
    exit 1
fi

# Check if we can connect to cluster
if ! kubectl cluster-info &> /dev/null; then
    echo -e "${RED}Error: Cannot connect to Kubernetes cluster${NC}"
    exit 1
fi

# Function to validate VM configuration
validate_vm() {
    local file=$1
    local name=$(basename "$file" .yaml)
    
    # Check if this VM targets r630-01
    local node=$(kubectl apply --dry-run=client -f "$file" -o json 2>/dev/null | jq -r '.spec.forProvider.node // ""' 2>/dev/null || echo "")
    
    if [[ "$node" != "r630-01" ]]; then
        return 2  # Skip this VM (not targeting r630-01)
    fi
    
    echo -e "${BLUE}Validating $name...${NC}"
    
    # Validate the configuration
    if kubectl apply --dry-run=client -f "$file" &>/dev/null; then
        # Extract configuration details
        local config=$(kubectl apply --dry-run=client -f "$file" -o json 2>/dev/null)
        local cpu=$(echo "$config" | jq -r '.spec.forProvider.cpu // "N/A"')
        local memory=$(echo "$config" | jq -r '.spec.forProvider.memory // "N/A"')
        local disk=$(echo "$config" | jq -r '.spec.forProvider.disk // "N/A"')
        local storage=$(echo "$config" | jq -r '.spec.forProvider.storage // "N/A"')
        local image=$(echo "$config" | jq -r '.spec.forProvider.image // "N/A"')
        local site=$(echo "$config" | jq -r '.spec.forProvider.site // "N/A"')
        
        echo -e "  ${GREEN}✓${NC} Configuration valid"
        echo -e "    CPU: $cpu cores"
        echo -e "    Memory: $memory"
        echo -e "    Disk: $disk"
        echo -e "    Storage: $storage"
        echo -e "    Image: $image"
        echo -e "    Site: $site"
        
        # Check if VM already exists
        if kubectl get proxmoxvm "$name" &>/dev/null 2>&1; then
            local existing_node=$(kubectl get proxmoxvm "$name" -o jsonpath='{.spec.forProvider.node}' 2>/dev/null || echo "")
            if [[ "$existing_node" == "r630-01" ]]; then
                echo -e "    ${YELLOW}⚠${NC} VM already exists (will be updated)"
            else
                echo -e "    ${YELLOW}⚠${NC} VM exists on different node: $existing_node"
            fi
        else
            echo -e "    ${CYAN}→${NC} New VM will be created"
        fi
        
        return 0
    else
        echo -e "  ${RED}✗${NC} Configuration validation failed"
        kubectl apply --dry-run=client -f "$file" 2>&1 | head -5
        return 1
    fi
}

# Collect all VMs targeting r630-01
echo "=========================================="
echo "Phase 1: Core Infrastructure"
echo "=========================================="
echo ""

CORE_VMS=(
    "examples/production/nginx-proxy-vm.yaml"
    "examples/production/cloudflare-tunnel-vm.yaml"
)

CORE_COUNT=0
CORE_VALID=0
CORE_INVALID=0

for vm in "${CORE_VMS[@]}"; do
    if [[ -f "$PROJECT_ROOT/$vm" ]]; then
        validate_vm "$PROJECT_ROOT/$vm"; result=$?
        if [[ $result -eq 0 ]]; then
            ((CORE_VALID++)) || true
            ((CORE_COUNT++)) || true
        elif [[ $result -eq 1 ]]; then
            ((CORE_INVALID++)) || true
            ((CORE_COUNT++)) || true
        fi
    fi
done

echo ""
sleep 1

# Phase 2: Phoenix Infrastructure
echo "=========================================="
echo "Phase 2: Phoenix Infrastructure"
echo "=========================================="
echo ""

PHOENIX_VMS=(
    "examples/production/phoenix/git-server.yaml"
    "examples/production/phoenix/email-server.yaml"
    "examples/production/phoenix/devops-runner.yaml"
    "examples/production/phoenix/codespaces-ide.yaml"
    "examples/production/phoenix/as4-gateway.yaml"
    "examples/production/phoenix/business-integration-gateway.yaml"
    "examples/production/phoenix/financial-messaging-gateway.yaml"
)

PHOENIX_COUNT=0
PHOENIX_VALID=0
PHOENIX_INVALID=0

for vm in "${PHOENIX_VMS[@]}"; do
    if [[ -f "$PROJECT_ROOT/$vm" ]]; then
        validate_vm "$PROJECT_ROOT/$vm"; result=$?
        if [[ $result -eq 0 ]]; then
            ((PHOENIX_VALID++)) || true
            ((PHOENIX_COUNT++)) || true
        elif [[ $result -eq 1 ]]; then
            ((PHOENIX_INVALID++)) || true
            ((PHOENIX_COUNT++)) || true
        fi
    fi
done

echo ""
sleep 1

# Phase 3: Blockchain Infrastructure
echo "=========================================="
echo "Phase 3: Blockchain Infrastructure"
echo "=========================================="
echo ""

# Validators
echo -e "${BLUE}Validating Validators...${NC}"
VALIDATOR_COUNT=0
VALIDATOR_VALID=0
VALIDATOR_INVALID=0

for i in {1..4}; do
    vm_file="$PROJECT_ROOT/examples/production/smom-dbis-138/validator-0$i.yaml"
    if [[ -f "$vm_file" ]]; then
        validate_vm "$vm_file"; result=$?
        if [[ $result -eq 0 ]]; then
            ((VALIDATOR_VALID++)) || true
            ((VALIDATOR_COUNT++)) || true
        elif [[ $result -eq 1 ]]; then
            ((VALIDATOR_INVALID++)) || true
            ((VALIDATOR_COUNT++)) || true
        fi
    fi
done

echo ""

# Sentries
echo -e "${BLUE}Validating Sentries...${NC}"
SENTRY_COUNT=0
SENTRY_VALID=0
SENTRY_INVALID=0

for i in {1..4}; do
    vm_file="$PROJECT_ROOT/examples/production/smom-dbis-138/sentry-0$i.yaml"
    if [[ -f "$vm_file" ]]; then
        validate_vm "$vm_file"; result=$?
        if [[ $result -eq 0 ]]; then
            ((SENTRY_VALID++)) || true
            ((SENTRY_COUNT++)) || true
        elif [[ $result -eq 1 ]]; then
            ((SENTRY_INVALID++)) || true
            ((SENTRY_COUNT++)) || true
        fi
    fi
done

echo ""

# RPC Nodes
echo -e "${BLUE}Validating RPC Nodes...${NC}"
RPC_COUNT=0
RPC_VALID=0
RPC_INVALID=0

for i in {1..4}; do
    vm_file="$PROJECT_ROOT/examples/production/smom-dbis-138/rpc-node-0$i.yaml"
    if [[ -f "$vm_file" ]]; then
        validate_vm "$vm_file"; result=$?
        if [[ $result -eq 0 ]]; then
            ((RPC_VALID++)) || true
            ((RPC_COUNT++)) || true
        elif [[ $result -eq 1 ]]; then
            ((RPC_INVALID++)) || true
            ((RPC_COUNT++)) || true
        fi
    fi
done

echo ""

# Services
echo -e "${BLUE}Validating Services...${NC}"
SERVICE_VMS=(
    "examples/production/smom-dbis-138/management.yaml"
    "examples/production/smom-dbis-138/monitoring.yaml"
    "examples/production/smom-dbis-138/services.yaml"
    "examples/production/smom-dbis-138/blockscout.yaml"
)

SERVICE_COUNT=0
SERVICE_VALID=0
SERVICE_INVALID=0

for vm in "${SERVICE_VMS[@]}"; do
    if [[ -f "$PROJECT_ROOT/$vm" ]]; then
        validate_vm "$PROJECT_ROOT/$vm"; result=$?
        if [[ $result -eq 0 ]]; then
            ((SERVICE_VALID++)) || true
            ((SERVICE_COUNT++)) || true
        elif [[ $result -eq 1 ]]; then
            ((SERVICE_INVALID++)) || true
            ((SERVICE_COUNT++)) || true
        fi
    fi
done

echo ""

# Additional VMs (basic, medium, large, vm-100)
echo "=========================================="
echo "Phase 4: Additional VMs"
echo "=========================================="
echo ""

ADDITIONAL_VMS=(
    "examples/production/basic-vm.yaml"
    "examples/production/medium-vm.yaml"
    "examples/production/large-vm.yaml"
    "examples/production/vm-100.yaml"
)

ADDITIONAL_COUNT=0
ADDITIONAL_VALID=0
ADDITIONAL_INVALID=0

for vm in "${ADDITIONAL_VMS[@]}"; do
    if [[ -f "$PROJECT_ROOT/$vm" ]]; then
        validate_vm "$PROJECT_ROOT/$vm"; result=$?
        if [[ $result -eq 0 ]]; then
            ((ADDITIONAL_VALID++)) || true
            ((ADDITIONAL_COUNT++)) || true
        elif [[ $result -eq 1 ]]; then
            ((ADDITIONAL_INVALID++)) || true
            ((ADDITIONAL_COUNT++)) || true
        fi
    fi
done

echo ""

# Summary
echo "=========================================="
echo "Dry Run Summary"
echo "=========================================="
echo ""

TOTAL_VALID=$((CORE_VALID + PHOENIX_VALID + VALIDATOR_VALID + SENTRY_VALID + RPC_VALID + SERVICE_VALID + ADDITIONAL_VALID))
TOTAL_INVALID=$((CORE_INVALID + PHOENIX_INVALID + VALIDATOR_INVALID + SENTRY_INVALID + RPC_INVALID + SERVICE_INVALID + ADDITIONAL_INVALID))
TOTAL_COUNT=$((CORE_COUNT + PHOENIX_COUNT + VALIDATOR_COUNT + SENTRY_COUNT + RPC_COUNT + SERVICE_COUNT + ADDITIONAL_COUNT))

echo "Core Infrastructure:"
echo "  Valid: $CORE_VALID"
echo "  Invalid: $CORE_INVALID"
echo ""

echo "Phoenix Infrastructure:"
echo "  Valid: $PHOENIX_VALID"
echo "  Invalid: $PHOENIX_INVALID"
echo ""

echo "Blockchain Infrastructure:"
echo "  Validators: $VALIDATOR_VALID valid, $VALIDATOR_INVALID invalid"
echo "  Sentries: $SENTRY_VALID valid, $SENTRY_INVALID invalid"
echo "  RPC Nodes: $RPC_VALID valid, $RPC_INVALID invalid"
echo "  Services: $SERVICE_VALID valid, $SERVICE_INVALID invalid"
echo ""

echo "Additional VMs:"
echo "  Valid: $ADDITIONAL_VALID"
echo "  Invalid: $ADDITIONAL_INVALID"
echo ""

echo "=========================================="
echo "Total VMs targeting r630-01: $TOTAL_COUNT"
echo -e "  ${GREEN}Valid: $TOTAL_VALID${NC}"
if [[ $TOTAL_INVALID -gt 0 ]]; then
    echo -e "  ${RED}Invalid: $TOTAL_INVALID${NC}"
else
    echo -e "  ${GREEN}Invalid: $TOTAL_INVALID${NC}"
fi
echo "=========================================="
echo ""

if [[ $TOTAL_INVALID -eq 0 ]]; then
    echo -e "${GREEN}✓ All VM configurations are valid!${NC}"
    echo ""
    echo "To deploy these VMs, run:"
    echo "  ./scripts/deploy-all-vms.sh"
    echo ""
    echo "Or deploy individually:"
    echo "  kubectl apply -f examples/production/<vm-file>.yaml"
    exit 0
else
    echo -e "${RED}✗ Some VM configurations have errors${NC}"
    echo "Please fix the invalid configurations before deploying."
    exit 1
fi

