#!/usr/bin/env bash

set -e

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

echo "╔════════════════════════════════════════════════════════════════╗"
echo "║     EXECUTING ALL DEPLOYMENT PHASES                               ║"
echo "╚════════════════════════════════════════════════════════════════╝"

# Phase 1: Key Vault Deployment
echo "=" | awk '{printf "%-64s\n", ""}'
echo "PHASE 1: KEY VAULT DEPLOYMENT"
echo "=" | awk '{printf "%-64s\n", ""}'

bash "$SCRIPT_DIR/deploy-keyvaults-only.sh"

if [ $? -ne 0 ]; then
    echo "❌ Phase 1 failed. Stopping deployment."
    exit 1
fi

echo "✅ Phase 1 complete. Waiting 10 seconds before Phase 2..."
sleep 10

# Phase 2: Store Node Secrets
echo "=" | awk '{printf "%-64s\n", ""}'
echo "PHASE 2: STORE NODE SECRETS"
echo "=" | awk '{printf "%-64s\n", ""}'

bash "$PROJECT_ROOT/scripts/key-management/store-nodes-in-keyvault.sh"

if [ $? -ne 0 ]; then
    echo "❌ Phase 2 failed. Stopping deployment."
    exit 1
fi

echo "✅ Phase 2 complete. Waiting 10 seconds before Phase 3..."
sleep 10

# Phase 3: AKS Cluster Deployment
echo "=" | awk '{printf "%-64s\n", ""}'
echo "PHASE 3: AKS CLUSTER DEPLOYMENT"
echo "=" | awk '{printf "%-64s\n", ""}'

cd "$PROJECT_ROOT/terraform/well-architected/cloud-sovereignty"

if [ ! -f "terraform.tfvars.36regions" ]; then
    echo "❌ Error: terraform.tfvars.36regions not found"
    exit 1
fi

# Ensure deploy_aks_clusters is true
if ! grep -q "deploy_aks_clusters = true" terraform.tfvars.36regions; then
    echo "Updating terraform.tfvars.36regions to enable AKS deployment..."
    sed -i 's/deploy_aks_clusters = false/deploy_aks_clusters = true/' terraform.tfvars.36regions
fi

echo "Running Terraform plan for AKS clusters..."
terraform plan -var-file=terraform.tfvars.36regions -out=tfplan.aks

echo "Applying Terraform plan for AKS clusters..."
echo "This will deploy AKS clusters across 36 regions with:"
echo "  • 72 system nodes (D2plsv6)"
echo "  • 36 validator nodes (D2psv6)"
echo "Press Ctrl+C to cancel, or wait 10 seconds to continue..."
sleep 10

terraform apply tfplan.aks

if [ $? -ne 0 ]; then
    echo "❌ Phase 3 failed. Check Terraform output above."
    exit 1
fi

echo "=" | awk '{printf "%-64s\n", ""}'
echo "✅ ALL PHASES COMPLETE"
echo "=" | awk '{printf "%-64s\n", ""}'

echo "Next steps:"
echo "  1. Update enode URLs with actual node IP addresses"
echo "  2. Deploy Besu validator pods"

