#!/usr/bin/env bash
# Wait for Phase 2 completion and then execute all remaining phases
# Monitors Terraform apply and automatically proceeds with all phases

set -euo pipefail

PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
PID_FILE="/tmp/terraform-apply-36regions.pid"
TF_DIR="$PROJECT_ROOT/terraform/well-architected/cloud-sovereignty"

echo "╔════════════════════════════════════════════════════════════════╗"
echo "║     WAIT AND COMPLETE ALL PHASES                              ║"
echo "╚════════════════════════════════════════════════════════════════╝"
echo ""

# Check if deployment is running
if [ -f "$PID_FILE" ]; then
    PID=$(cat "$PID_FILE")
    if ps -p "$PID" > /dev/null 2>&1; then
        echo "⏳ Waiting for Phase 2 (Infrastructure Deployment) to complete..."
        echo "   PID: $PID"
        echo ""
        
        # Monitor until completion
        while ps -p "$PID" > /dev/null 2>&1; do
            echo -n "."
            sleep 30
        done
        
        echo ""
        echo ""
        echo "✅ Phase 2 complete!"
        echo ""
        
        # Wait a bit for resources to stabilize
        echo "⏳ Waiting 60 seconds for resources to stabilize..."
        sleep 60
    else
        echo "✅ Phase 2 already completed"
    fi
else
    echo "⚠️  No deployment PID found. Checking current status..."
fi

# Verify deployment
echo ""
echo "🔍 Verifying deployment..."
cd "$TF_DIR"

if terraform output region_resources > /dev/null 2>&1; then
    echo "✅ Infrastructure resources deployed"
    
    # Proceed with all remaining phases
    echo ""
    echo "🚀 Proceeding with all remaining phases..."
    echo ""
    
    "$PROJECT_ROOT/scripts/deployment/complete-all-phases-parallel.sh"
else
    echo "❌ Infrastructure deployment not found. Please check logs:"
    echo "   ls -t /tmp/terraform-apply-36regions-*.log | head -1"
    exit 1
fi

echo ""

