#!/bin/bash
# Pre-Deployment Verification Script
# Verifies all pre-deployment requirements are met

set -e

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

ERRORS=0
WARNINGS=0

echo "=========================================="
echo "Pre-Deployment Verification"
echo "=========================================="
echo ""

# 1. Check namespace
echo "1. Checking crossplane-system namespace..."
if kubectl get namespace crossplane-system &>/dev/null; then
    echo -e "${GREEN}✓${NC} Namespace exists"
else
    echo -e "${RED}✗${NC} Namespace missing"
    ((ERRORS++))
fi

# 2. Check provider pod
echo ""
echo "2. Checking provider pod..."
POD_STATUS=$(kubectl get pods -n crossplane-system -l app=crossplane-provider-proxmox -o jsonpath='{.items[0].status.phase}' 2>/dev/null || echo "NOT_FOUND")
if [[ "$POD_STATUS" == "Running" ]]; then
    echo -e "${GREEN}✓${NC} Provider pod is running"
    READY=$(kubectl get pods -n crossplane-system -l app=crossplane-provider-proxmox -o jsonpath='{.items[0].status.containerStatuses[0].ready}' 2>/dev/null)
    if [[ "$READY" == "true" ]]; then
        echo -e "${GREEN}✓${NC} Provider pod is ready"
    else
        echo -e "${YELLOW}⚠${NC} Provider pod not ready yet"
        ((WARNINGS++))
    fi
else
    echo -e "${RED}✗${NC} Provider pod not running (status: $POD_STATUS)"
    ((ERRORS++))
fi

# 3. Check ProviderConfig
echo ""
echo "3. Checking ProviderConfig..."
if kubectl get providerconfig proxmox-provider-config -n crossplane-system &>/dev/null; then
    echo -e "${GREEN}✓${NC} ProviderConfig exists"
    
    # Check sites
    SITES=$(kubectl get providerconfig proxmox-provider-config -n crossplane-system -o jsonpath='{.spec.sites[*].name}' 2>/dev/null)
    if [[ "$SITES" == *"site-1"* && "$SITES" == *"site-2"* ]]; then
        echo -e "${GREEN}✓${NC} Both sites configured (site-1, site-2)"
    else
        echo -e "${RED}✗${NC} Sites not correctly configured: $SITES"
        ((ERRORS++))
    fi
else
    echo -e "${RED}✗${NC} ProviderConfig not found"
    ((ERRORS++))
fi

# 4. Check secret
echo ""
echo "4. Checking credentials secret..."
if kubectl get secret proxmox-credentials -n crossplane-system &>/dev/null; then
    echo -e "${GREEN}✓${NC} Secret exists"
    
    # Check secret keys
    KEYS=$(kubectl get secret proxmox-credentials -n crossplane-system -o jsonpath='{.data}' 2>/dev/null | jq -r 'keys[]' 2>/dev/null || echo "")
    if [[ "$KEYS" == *"tokenid"* && "$KEYS" == *"token"* ]] || [[ "$KEYS" == *"username"* && "$KEYS" == *"password"* ]]; then
        echo -e "${GREEN}✓${NC} Secret has correct format"
    else
        echo -e "${YELLOW}⚠${NC} Secret format may be incorrect (keys: $KEYS)"
        ((WARNINGS++))
    fi
else
    echo -e "${RED}✗${NC} Secret not found"
    ((ERRORS++))
fi

# 5. Check CRDs
echo ""
echo "5. Checking CRDs..."
REQUIRED_CRDS=("proxmoxvms.proxmox.sankofa.nexus" "providerconfigs.proxmox.sankofa.nexus")
for CRD in "${REQUIRED_CRDS[@]}"; do
    if kubectl get crd "$CRD" &>/dev/null; then
        echo -e "${GREEN}✓${NC} $CRD installed"
    else
        echo -e "${RED}✗${NC} $CRD not installed"
        ((ERRORS++))
    fi
done

# 6. Check provider logs for errors
echo ""
echo "6. Checking provider logs..."
LOG_ERRORS=$(kubectl logs -n crossplane-system -l app=crossplane-provider-proxmox --tail=50 2>&1 | grep -i "error" | grep -v "CRD" | wc -l)
if [[ $LOG_ERRORS -eq 0 ]]; then
    echo -e "${GREEN}✓${NC} No critical errors in logs"
else
    echo -e "${YELLOW}⚠${NC} Found $LOG_ERRORS error messages in logs (may be non-critical)"
    ((WARNINGS++))
fi

# 7. Verify site endpoints
echo ""
echo "7. Verifying site endpoints..."
SITE1_ENDPOINT=$(kubectl get providerconfig proxmox-provider-config -n crossplane-system -o jsonpath='{.spec.sites[?(@.name=="site-1")].endpoint}' 2>/dev/null)
SITE2_ENDPOINT=$(kubectl get providerconfig proxmox-provider-config -n crossplane-system -o jsonpath='{.spec.sites[?(@.name=="site-2")].endpoint}' 2>/dev/null)

if [[ "$SITE1_ENDPOINT" == "https://192.168.11.10:8006" ]]; then
    echo -e "${GREEN}✓${NC} Site-1 endpoint correct: $SITE1_ENDPOINT"
else
    echo -e "${RED}✗${NC} Site-1 endpoint incorrect: $SITE1_ENDPOINT"
    ((ERRORS++))
fi

if [[ "$SITE2_ENDPOINT" == "https://192.168.11.11:8006" ]]; then
    echo -e "${GREEN}✓${NC} Site-2 endpoint correct: $SITE2_ENDPOINT"
else
    echo -e "${RED}✗${NC} Site-2 endpoint incorrect: $SITE2_ENDPOINT"
    ((ERRORS++))
fi

echo ""
echo "=========================================="
echo "Verification Complete"
echo "=========================================="
echo "Errors: $ERRORS"
echo "Warnings: $WARNINGS"

if [[ $ERRORS -eq 0 && $WARNINGS -eq 0 ]]; then
    echo -e "${GREEN}✓ All checks passed! Ready for deployment.${NC}"
    exit 0
elif [[ $ERRORS -eq 0 ]]; then
    echo -e "${YELLOW}⚠ All critical checks passed with minor warnings.${NC}"
    exit 0
else
    echo -e "${RED}✗ Critical errors found. Please fix before deployment.${NC}"
    exit 1
fi

