#!/usr/bin/env bash
# Complete All Phases - Full Parallel Execution
# Orchestrates all deployment phases for 36-region deployment

set -euo pipefail

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

echo "╔════════════════════════════════════════════════════════════════╗"
echo "║     COMPLETE ALL PHASES - FULL PARALLEL EXECUTION             ║"
echo "╚════════════════════════════════════════════════════════════════╝"
echo ""

# Phase 2: Infrastructure Deployment
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "📋 PHASE 2: INFRASTRUCTURE DEPLOYMENT"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""

# Check if Phase 2 is complete
TF_DIR="$PROJECT_ROOT/terraform/well-architected/cloud-sovereignty"
cd "$TF_DIR"

if terraform output region_resources > /dev/null 2>&1; then
    echo "✅ Phase 2: Infrastructure already deployed"
    
    # Verify clusters are ready
    echo "🔍 Verifying cluster readiness..."
    "$PROJECT_ROOT/scripts/deployment/verify-36-region-clusters.sh"
    
    READY_COUNT=$(az aks list --query "[?contains(name, 'az-p-') && contains(name, '-aks-main') && provisioningState=='Succeeded'].name" -o tsv 2>/dev/null | wc -l || echo "0")
    
    if [ "$READY_COUNT" -ge 36 ]; then
        echo "✅ All 36 clusters are ready!"
        echo ""
        
        # Phase 3: Kubernetes Configuration (can start in parallel for ready clusters)
        echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
        echo "📋 PHASE 3: KUBERNETES CONFIGURATION"
        echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
        echo ""
        echo "🚀 Starting Phase 3 in parallel across all ready clusters..."
        echo ""
        
        # Get kubeconfigs for all clusters
        echo "📥 Getting kubeconfig for all clusters..."
        az aks list --query "[?contains(name, 'az-p-') && contains(name, '-aks-main') && provisioningState=='Succeeded'].{name:name, resourceGroup:resourceGroup}" -o json | \
            jq -r '.[] | "\(.name)|\(.resourceGroup)"' | \
            while IFS='|' read -r name rg; do
                az aks get-credentials --resource-group "$rg" --name "$name" --overwrite-existing >/dev/null 2>&1 &
            done
        wait
        echo "✅ Kubeconfigs configured for all clusters"
        echo ""
        
        # Phase 4-8 will be executed as scripts become available
        echo "📋 Next phases will be executed as infrastructure becomes available:"
        echo "   • Phase 4: Besu Network Deployment"
        echo "   • Phase 5: Application Stack Deployment"
        echo "   • Phase 6: Cross-Chain & Integration"
        echo "   • Phase 7: Verification & Testing"
        echo "   • Phase 8: Documentation & Handoff"
        echo ""
    else
        echo "⏳ Waiting for all clusters to be ready ($READY_COUNT/36 ready)..."
        echo "   Run this script again once all clusters are ready"
    fi
else
    echo "⏳ Phase 2: Infrastructure deployment in progress..."
    echo "   Monitor with: ./scripts/deployment/monitor-36-region-deployment.sh"
    echo ""
    echo "   Once complete, run this script again to proceed with Phase 3"
fi

echo ""

