#!/usr/bin/env bash
# Verify 36-Region AKS Clusters Status
# Checks provisioning state and gets cluster information

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/../lib/init.sh"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
# Load .env via dotenv (RPC CR/LF trim). Fallback: raw source.
if [[ -f "$SCRIPT_DIR/../lib/deployment/dotenv.sh" ]]; then
  # shellcheck disable=SC1090
  source "$SCRIPT_DIR/../lib/deployment/dotenv.sh"
  load_deployment_env --repo-root "${PROJECT_ROOT:-$REPO_ROOT}"
elif [[ -n "${PROJECT_ROOT:-}" && -f "$PROJECT_ROOT/.env" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$PROJECT_ROOT/.env"
  set +a
elif [[ -n "${REPO_ROOT:-}" && -f "$REPO_ROOT/.env" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$REPO_ROOT/.env"
  set +a
fi

# Load environment variables
if [ -f "$PROJECT_ROOT/.env" ]; then
    export $(grep -v '^#' "$PROJECT_ROOT/.env" | xargs)
fi

SUBSCRIPTION_ID="${AZURE_SUBSCRIPTION_ID:-fc08d829-4f14-413d-ab27-ce024425db0b}"

echo "╔════════════════════════════════════════════════════════════════╗"
echo "║     VERIFYING 36-REGION AKS CLUSTERS                           ║"
echo "╚════════════════════════════════════════════════════════════════╝"

az account set --subscription "$SUBSCRIPTION_ID" >/dev/null 2>&1

echo "📊 Checking cluster status..."

# Get all clusters matching naming pattern
clusters=$(az aks list --query "[?contains(name, 'az-p-') && contains(name, '-aks-main')].{name:name, resourceGroup:resourceGroup, location:location, provisioningState:provisioningState, powerState:powerState.code}" -o json)

# Count by status
ready=$(echo "$clusters" | jq '[.[] | select(.provisioningState == "Succeeded" and (.powerState == null or .powerState == "Running"))] | length')
creating=$(echo "$clusters" | jq '[.[] | select(.provisioningState == "Creating")] | length')
failed=$(echo "$clusters" | jq '[.[] | select(.provisioningState == "Failed")] | length')
canceled=$(echo "$clusters" | jq '[.[] | select(.provisioningState == "Canceled")] | length')
total=$(echo "$clusters" | jq '. | length')

echo "📈 Cluster Status Summary:"
echo "   • Total clusters: $total"
echo "   • Ready (Succeeded): $ready"
echo "   • Creating: $creating"
echo "   • Failed: $failed"
echo "   • Canceled: $canceled"

if [ "$ready" -eq "$total" ] && [ "$total" -eq 36 ]; then
    echo "✅ All 36 clusters are ready!"
    echo "📋 Getting kubeconfig for all clusters..."
    
    # Get kubeconfig for each ready cluster
    echo "$clusters" | jq -r '.[] | select(.provisioningState == "Succeeded") | "\(.name)|\(.resourceGroup)"' | while IFS='|' read -r name rg; do
        echo "   • Getting kubeconfig for $name..."
        az aks get-credentials --resource-group "$rg" --name "$name" --overwrite-existing >/dev/null 2>&1 || true
    done
    
    echo "✅ Kubeconfigs configured!"
else
    echo "⚠️  Not all clusters are ready yet."
    
    if [ "$creating" -gt 0 ]; then
        echo "⏳ Creating clusters ($creating):"
        echo "$clusters" | jq -r '.[] | select(.provisioningState == "Creating") | "   • \(.name) (\(.location))"' || true
    fi
    
    if [ "$failed" -gt 0 ]; then
        echo "❌ Failed clusters ($failed):"
        echo "$clusters" | jq -r '.[] | select(.provisioningState == "Failed") | "   • \(.name) (\(.location))"' || true
    fi
    
    if [ "$canceled" -gt 0 ]; then
        echo "⚠️  Canceled clusters ($canceled):"
        echo "$clusters" | jq -r '.[] | select(.provisioningState == "Canceled") | "   • \(.name) (\(.location))"' || true
    fi
fi

echo "📄 Full cluster list:"
echo "$clusters" | jq -r '.[] | "\(.name) | \(.location) | \(.provisioningState) | \(.powerState // "N/A")"' | column -t -s '|' || true

