#!/usr/bin/env bash
# Wait for infrastructure to be ready, then run all next steps

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

REGIONS=(
  "northeurope" "uksouth" "ukwest" "francecentral" "germanywestcentral"
  "switzerlandnorth" "italynorth" "norwayeast" "polandcentral" "spaincentral"
  "swedencentral" "belgiumcentral" "australiaeast" "australiasoutheast" "eastasia"
  "southeastasia" "centralindia" "southindia" "japaneast"
  "japanwest" "koreacentral" "koreasouth" "canadacentral" "mexicocentral"
)

MAX_WAIT_MINUTES=60
CHECK_INTERVAL=60

echo "=== Waiting for Infrastructure and Running Next Steps ==="
echo "This script will:"
echo "  1. Wait for AKS clusters to be ready (max $MAX_WAIT_MINUTES minutes)"
echo "  2. Run verification"
echo "  3. Configure Kubernetes"
echo "  4. Deploy Besu network"
echo "  5. Deploy contracts"
echo "  6. Deploy monitoring"

# Function to check if cluster is ready
check_cluster_ready() {
  local region=$1
  local rg_name="az-p-${region}-rg-comp-001"
  local cluster_name="az-p-${region}-aks-main"
  
  az aks show --resource-group "$rg_name" --name "$cluster_name" --query provisioningState -o tsv 2>/dev/null | grep -q "Succeeded"
}

# Function to count ready clusters
count_ready_clusters() {
  local count=0
  for region in "${REGIONS[@]}"; do
    if check_cluster_ready "$region"; then
      ((count++))
    fi
  done
  echo "$count"
}

# Wait for clusters to be ready
echo "Waiting for AKS clusters to be ready..."
echo "Checking every $CHECK_INTERVAL seconds..."

start_time=$(date +%s)
max_wait_seconds=$((MAX_WAIT_MINUTES * 60))

while true; do
  ready_count=$(count_ready_clusters)
  total_regions=${#REGIONS[@]}
  
  elapsed=$(( $(date +%s) - start_time ))
  elapsed_minutes=$((elapsed / 60))
  
  echo "[$(date +%H:%M:%S)] Ready: $ready_count/$total_regions clusters (${elapsed_minutes}m elapsed)"
  
  if [ "$ready_count" -ge "$total_regions" ]; then
    echo "✅ All clusters are ready!"
    break
  fi
  
  if [ "$elapsed" -ge "$max_wait_seconds" ]; then
    echo "⚠️  Timeout reached. Proceeding with available clusters..."
    break
  fi
  
  sleep $CHECK_INTERVAL
done

echo "=== Running Next Steps ==="

# Phase 1: Verification
echo "Phase 1: Verification"
"$SCRIPT_DIR/verify-all-max-parallel.sh"

# Phase 2: Kubernetes Configuration
echo "Phase 2: Kubernetes Configuration"
"$SCRIPT_DIR/configure-kubernetes-max-parallel.sh"

# Phase 3: Besu Deployment
echo "Phase 3: Besu Deployment"
"$SCRIPT_DIR/deploy-besu-max-parallel.sh"

# Phase 4: Contracts
echo "Phase 4: Contract Deployment"
"$SCRIPT_DIR/deploy-contracts-parallel.sh"

# Phase 5: Monitoring
echo "Phase 5: Monitoring Deployment"
"$SCRIPT_DIR/deploy-monitoring-parallel.sh"

echo "=== ✅ All Next Steps Complete ==="
