#!/usr/bin/env bash
# Wait for Terraform to complete, then run all next steps automatically

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 "║   WAIT FOR INFRASTRUCTURE & RUN ALL NEXT STEPS                 ║"
echo "╚════════════════════════════════════════════════════════════════╝"

MAX_WAIT_MINUTES=120
CHECK_INTERVAL=60
CHECK_COUNT=0
MAX_CHECKS=$((MAX_WAIT_MINUTES * 60 / CHECK_INTERVAL))

echo "Waiting for Terraform deployment to complete..."
echo "  Max wait: $MAX_WAIT_MINUTES minutes"
echo "  Check interval: $CHECK_INTERVAL seconds"

while [ $CHECK_COUNT -lt $MAX_CHECKS ]; do
  CHECK_COUNT=$((CHECK_COUNT + 1))
  
  # Check if Terraform is still running
  if ps aux | grep -i "terraform apply" | grep -v grep > /dev/null; then
    TERRAFORM_PID=$(ps aux | grep -i "terraform apply" | grep -v grep | awk '{print $2}' | head -1)
    RUNTIME=$(ps -p $TERRAFORM_PID -o etime= 2>/dev/null | tr -d ' ' || echo "unknown")
    echo "[$CHECK_COUNT/$MAX_CHECKS] Terraform still running (Runtime: $RUNTIME)..."
  else
    echo "[$CHECK_COUNT/$MAX_CHECKS] Terraform process not found - checking completion..."
    
    # Check if deployment completed successfully
    if [ -f /tmp/terraform-apply-unlocked.log ] && tail -10 /tmp/terraform-apply-unlocked.log | grep -q "Apply complete"; then
      echo "✅ Infrastructure deployment COMPLETE!"
      break
    else
      echo "  ⚠️  Terraform stopped but completion not confirmed"
      echo "  Checking logs..."
      if [ -f /tmp/terraform-apply-unlocked.log ]; then
        tail -5 /tmp/terraform-apply-unlocked.log | grep -E "complete|Error|error" || echo "  No clear completion status"
      fi
    fi
  fi
  
  if [ $CHECK_COUNT -lt $MAX_CHECKS ]; then
    sleep $CHECK_INTERVAL
  fi
done

if [ $CHECK_COUNT -ge $MAX_CHECKS ]; then
  echo "⚠️  Timeout waiting for Terraform to complete"
  echo "   Proceeding anyway - you can check status manually"
fi

echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "Running All Next Steps..."
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

# Run all next steps
if [ -f "$SCRIPT_DIR/run-all-next-steps.sh" ]; then
  bash "$SCRIPT_DIR/run-all-next-steps.sh" 2>&1 | tee /tmp/all-next-steps-execution.log
else
  echo "❌ Error: run-all-next-steps.sh not found"
  exit 1
fi

echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "✅ ALL NEXT STEPS COMPLETE"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "Execution log: /tmp/all-next-steps-execution.log"
