#!/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)"
TERRAFORM_DIR="$PROJECT_ROOT/terraform/well-architected/cloud-sovereignty"

echo "╔════════════════════════════════════════════════════════════════╗"
echo "║     COMPLETE DEPLOYMENT - ALL PHASES                              ║"
echo "╚════════════════════════════════════════════════════════════════╝"

# Phase 1: Key Vaults
echo "======================================================================"
echo "PHASE 1: KEY VAULT DEPLOYMENT"
echo "======================================================================"

cd "$TERRAFORM_DIR"

# Create Phase 1 config
if [ ! -f "terraform.tfvars.keyvaults" ]; then
    cat terraform.tfvars.36regions | sed 's/deploy_aks_clusters = true/deploy_aks_clusters = false/' > terraform.tfvars.keyvaults
fi

echo "Step 1.1: Running Terraform plan for Key Vaults..."
terraform plan -var-file=terraform.tfvars.keyvaults -out=tfplan.keyvaults -no-color 2>&1 | tee /tmp/terraform-plan-phase1.log | tail -20

PLAN_EXIT_CODE=${PIPESTATUS[0]}

if [ $PLAN_EXIT_CODE -ne 0 ]; then
    echo "❌ Terraform plan failed. Check logs: /tmp/terraform-plan-phase1.log"
    exit 1
fi

echo "Step 1.2: Applying Terraform plan for Key Vaults..."
echo "This will create Key Vaults across 36 regions..."
echo "Press Ctrl+C within 5 seconds to cancel..."
sleep 5

terraform apply tfplan.keyvaults -no-color 2>&1 | tee /tmp/terraform-apply-phase1.log | tail -50

APPLY_EXIT_CODE=${PIPESTATUS[0]}

if [ $APPLY_EXIT_CODE -ne 0 ]; then
    echo "❌ Terraform apply failed. Check logs: /tmp/terraform-apply-phase1.log"
    exit 1
fi

echo "✅ Phase 1 complete: Key Vaults deployed"

# Phase 2: Store Node Secrets
echo "======================================================================"
echo "PHASE 2: STORE NODE SECRETS"
echo "======================================================================"

cd "$PROJECT_ROOT"
# 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

bash scripts/key-management/store-nodes-in-keyvault.sh 2>&1 | tee /tmp/store-secrets.log

if [ ${PIPESTATUS[0]} -ne 0 ]; then
    echo "❌ Failed to store node secrets. Check logs: /tmp/store-secrets.log"
    exit 1
fi

echo "✅ Phase 2 complete: Node secrets stored"

# Phase 3: AKS Clusters
echo "======================================================================"
echo "PHASE 3: AKS CLUSTER DEPLOYMENT"
echo "======================================================================"

cd "$TERRAFORM_DIR"

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

echo "Step 3.1: Running Terraform plan for AKS clusters..."
terraform plan -var-file=terraform.tfvars.36regions -out=tfplan.aks -no-color 2>&1 | tee /tmp/terraform-plan-phase3.log | tail -20

PLAN_EXIT_CODE=${PIPESTATUS[0]}

if [ $PLAN_EXIT_CODE -ne 0 ]; then
    echo "❌ Terraform plan failed. Check logs: /tmp/terraform-plan-phase3.log"
    exit 1
fi

echo "Step 3.2: Applying Terraform plan for AKS clusters..."
echo "This will create AKS clusters with:"
echo "  • 72 system nodes (D2plsv6)"
echo "  • 36 validator nodes (D2psv6)"
echo "  • Across 36 regions"
echo "Press Ctrl+C within 10 seconds to cancel..."
sleep 10

terraform apply tfplan.aks -no-color 2>&1 | tee /tmp/terraform-apply-phase3.log

APPLY_EXIT_CODE=${PIPESTATUS[0]}

if [ $APPLY_EXIT_CODE -ne 0 ]; then
    echo "❌ Terraform apply failed. Check logs: /tmp/terraform-apply-phase3.log"
    exit 1
fi

echo "======================================================================"
echo "✅ ALL PHASES COMPLETE"
echo "======================================================================"

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

# Cleanup
rm -f terraform.tfvars.keyvaults

