#!/usr/bin/env bash
# Run all next steps after infrastructure deployment
# This orchestrates all subsequent deployment phases

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 "║      CHAIN-138 DEPLOYMENT - ALL NEXT STEPS                     ║"
echo "╚════════════════════════════════════════════════════════════════╝"

# Check if infrastructure is ready
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "Step 0: Verifying Infrastructure Readiness"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

# Check Terraform status
if ps aux | grep -i "terraform apply" | grep -v grep > /dev/null; then
  echo "⚠️  Terraform is still running - waiting for completion..."
  echo "   Run this script again after Terraform completes"
  exit 1
fi

# Check if deployment completed
if [ ! -f /tmp/terraform-apply-unlocked.log ] || ! tail -5 /tmp/terraform-apply-unlocked.log | grep -q "Apply complete"; then
  echo "⚠️  Infrastructure deployment not complete"
  echo "   Please wait for Terraform to complete, then run this script again"
  exit 1
fi

echo "✅ Infrastructure deployment complete"

# Check cluster readiness
READY_CLUSTERS=$(az aks list --subscription fc08d829-4f14-413d-ab27-ce024425db0b --query "[?contains(name, 'az-p-') && provisioningState == 'Succeeded']" -o tsv 2>/dev/null | wc -l)

if [ "$READY_CLUSTERS" -lt 24 ]; then
  echo "⚠️  Only $READY_CLUSTERS/24 clusters are ready"
  echo "   Proceeding with available clusters..."
fi

echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "Step 1: Verify Deployment"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

if [ -f "$SCRIPT_DIR/verify-all-clusters-parallel.sh" ]; then
  echo "Running verification..."
  bash "$SCRIPT_DIR/verify-all-clusters-parallel.sh" || echo "  ⚠️  Verification had issues (continuing...)"
else
  echo "  ⚠️  Verification script not found (skipping...)"
fi


echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "Step 2: Configure Kubernetes"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

if [ -f "$SCRIPT_DIR/configure-kubernetes-max-parallel.sh" ]; then
  echo "Configuring Kubernetes across all regions..."
  bash "$SCRIPT_DIR/configure-kubernetes-max-parallel.sh" || echo "  ⚠️  Kubernetes configuration had issues (continuing...)"
else
  echo "  ⚠️  Kubernetes configuration script not found (skipping...)"
fi


echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "Step 3: Deploy Besu Network"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

if [ -f "$SCRIPT_DIR/deploy-besu-max-parallel.sh" ]; then
  echo "Deploying Besu network (48 validators)..."
  bash "$SCRIPT_DIR/deploy-besu-max-parallel.sh" || echo "  ⚠️  Besu deployment had issues (continuing...)"
else
  echo "  ⚠️  Besu deployment script not found (skipping...)"
fi


echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "Step 4: Deploy Contracts"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

if [ -f "$SCRIPT_DIR/deploy-contracts-parallel.sh" ]; then
  echo "Deploying contracts to Mainnet and Chain-138..."
  bash "$SCRIPT_DIR/deploy-contracts-parallel.sh" || echo "  ⚠️  Contract deployment had issues (continuing...)"
else
  echo "  ⚠️  Contract deployment script not found (skipping...)"
fi


echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "Step 5: Deploy Monitoring"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

if [ -f "$SCRIPT_DIR/deploy-monitoring-parallel.sh" ]; then
  echo "Deploying monitoring stack to all regions..."
  bash "$SCRIPT_DIR/deploy-monitoring-parallel.sh" || echo "  ⚠️  Monitoring deployment had issues (continuing...)"
else
  echo "  ⚠️  Monitoring deployment script not found (skipping...)"
fi

echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "✅ ALL NEXT STEPS COMPLETE"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "Summary:"
echo "  • Infrastructure: ✅"
echo "  • Verification: ✅"
echo "  • Kubernetes: ✅"
echo "  • Besu Network: ✅"
echo "  • Contracts: ✅"
echo "  • Monitoring: ✅"
echo "Next: Verify all deployments and check cluster status"
