#!/usr/bin/env bash
# Check infrastructure status and proceed with next steps if ready

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/../lib/init.sh"

echo "=== Checking Infrastructure Readiness ==="

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

echo "Cluster Status:"
echo "  Ready: $READY/$TOTAL"
echo "  Creating: $CREATING"

# Check Terraform log
TF_COMPLETE=false
if [ -f /tmp/terraform-apply-unlocked.log ]; then
  if tail -30 /tmp/terraform-apply-unlocked.log | grep -qi "Apply complete"; then
    TF_COMPLETE=true
    echo "✅ Terraform deployment: COMPLETE"
  elif tail -30 /tmp/terraform-apply-unlocked.log | grep -qi "Error"; then
    echo "⚠️  Terraform deployment: ERRORS FOUND"
  else
    echo "⚠️  Terraform deployment: STATUS UNCLEAR"
  fi
fi


# Decision logic
if [ "$READY" -gt 0 ] || [ "$TF_COMPLETE" = true ]; then
  echo "✅ Infrastructure appears ready - Proceeding with next steps"
  bash "$SCRIPT_DIR/run-all-next-steps.sh" 2>&1 | tee /tmp/all-next-steps-execution.log
else
  echo "⚠️  Infrastructure not fully ready"
  echo "Options:"
  echo "  1. Wait for more clusters to become ready"
  echo "  2. Proceed with available clusters (use --force flag)"
  echo "To proceed anyway: $0 --force"
  
  if [ "$1" = "--force" ]; then
    echo "⚠️  Force mode: Proceeding with available infrastructure..."
    bash "$SCRIPT_DIR/run-all-next-steps.sh" 2>&1 | tee /tmp/all-next-steps-execution.log
  fi
fi
