#!/usr/bin/env bash
# Delete failed and canceled clusters so they can be recreated properly

set -e

SUBSCRIPTION_ID="fc08d829-4f14-413d-ab27-ce024425db0b"

echo "=== Deleting Failed/Canceled Clusters ==="
echo ""

# Get all failed and canceled clusters
CLUSTERS=$(az aks list --subscription "$SUBSCRIPTION_ID" --query "[?contains(name, 'az-p-') && (provisioningState == 'Failed' || provisioningState == 'Canceled')].{name:name, rg:resourceGroup, state:provisioningState}" -o json)

COUNT=$(echo "$CLUSTERS" | jq '. | length')

if [ "$COUNT" -eq 0 ]; then
  echo "✅ No failed/canceled clusters to delete"
  exit 0
fi

echo "Found $COUNT clusters to delete:"
echo "$CLUSTERS" | jq -r '.[] | "  - \(.name) (\(.state))"'
echo ""
read -p "Delete these clusters? (y/N) " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
  echo "Cancelled"
  exit 1
fi

echo ""
echo "Deleting clusters (this may take a few minutes)..."
echo ""

echo "$CLUSTERS" | jq -r '.[] | "\(.rg)|\(.name)"' | while IFS='|' read -r rg name; do
  echo "Deleting $name..."
  az aks delete --name "$name" --resource-group "$rg" --subscription "$SUBSCRIPTION_ID" --yes --no-wait 2>&1 | grep -v "Warning\|Deprecated" || true
  echo "  ✅ Delete initiated"
done

echo ""
echo "=== ✅ Deletes Initiated ==="
echo ""
echo "Clusters are being deleted in the background."
echo "Wait 5-10 minutes, then run:"
echo "  cd terraform/well-architected/cloud-sovereignty"
echo "  terraform apply -parallelism=128 -auto-approve"
