#!/usr/bin/env bash
# Deploy 36-Region Cloud for Sovereignty Infrastructure
# Phase 2: Infrastructure Deployment

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
TF_DIR="$PROJECT_ROOT/terraform/well-architected/cloud-sovereignty"

cd "$TF_DIR"

echo "╔════════════════════════════════════════════════════════════════╗"
echo "║     DEPLOYING 36-REGION INFRASTRUCTURE                         ║"
echo "╚════════════════════════════════════════════════════════════════╝"

# Check if plan exists
if [ ! -f "tfplan-36regions.out" ]; then
    echo "⚠️  Terraform plan not found. Running terraform plan..."
    terraform plan -var-file=terraform.tfvars.36regions -out=tfplan-36regions.out
fi

echo "🚀 Applying Terraform plan..."
echo "   This will deploy infrastructure across 36 regions"
echo "   Estimated time: 30-60 minutes"

# Apply with high parallelism for faster deployment
terraform apply -parallelism=128 tfplan-36regions.out

echo "✅ Infrastructure deployment complete!"
echo "📊 Next steps:"
echo "   1. Verify all AKS clusters are ready"
echo "   2. Get kubeconfig for all clusters"
echo "   3. Configure kubectl contexts"
echo "   4. Proceed to Phase 3: Kubernetes Configuration"
