#!/usr/bin/env bash
# Wait for Terraform to complete and monitor progress

set -e

echo "=== Waiting for Terraform to Complete ==="
echo ""

TERRAFORM_PID=""
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)
  echo "✅ Terraform Process Found (PID: $TERRAFORM_PID)"
  echo ""
  
  echo "Monitoring progress (press Ctrl+C to stop)..."
  echo ""
  
  while ps -p "$TERRAFORM_PID" > /dev/null 2>&1; do
    RUNTIME=$(ps -p "$TERRAFORM_PID" -o etime= 2>/dev/null | tr -d ' ' || echo "unknown")
    echo "[$(date +%H:%M:%S)] Terraform still running (Runtime: $RUNTIME)"
    
    if [ -f /tmp/terraform-apply-retry.log ]; then
      LOG_SIZE=$(du -h /tmp/terraform-apply-retry.log | cut -f1)
      LOG_LINES=$(wc -l < /tmp/terraform-apply-retry.log)
      echo "   Log: $LOG_SIZE, $LOG_LINES lines"
      
      # Check for completion
      if tail -5 /tmp/terraform-apply-retry.log | grep -q "Apply complete"; then
        echo ""
        echo "✅ Deployment Complete!"
        break
      fi
    fi
    
    sleep 30
  done
  
  if ! ps -p "$TERRAFORM_PID" > /dev/null 2>&1; then
    echo ""
    echo "✅ Terraform Process Completed"
    echo ""
    echo "Checking result..."
    if [ -f /tmp/terraform-apply-retry.log ]; then
      if tail -5 /tmp/terraform-apply-retry.log | grep -q "Apply complete"; then
        echo "✅ Deployment Successful!"
      elif tail -5 /tmp/terraform-apply-retry.log | grep -q "Error"; then
        echo "⚠️  Deployment had errors - check log"
      else
        echo "⚠️  Deployment status unclear - check log"
      fi
    fi
  fi
else
  echo "⚠️  No Terraform process found"
  echo ""
  echo "Checking for state lock..."
  cd terraform/well-architected/cloud-sovereignty
  echo "   State lock may be stale - consider force unlock if needed"
fi

echo ""
