#!/usr/bin/env bash
# Delete all failed and canceled clusters in parallel

set -e

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

echo "╔════════════════════════════════════════════════════════════════╗"
echo "║     PARALLEL CLUSTER DELETION                                   ║"
echo "╚════════════════════════════════════════════════════════════════╝"
echo ""

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

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

FAILED_COUNT=$(echo "$FAILED" | jq '. | length')
CANCELED_COUNT=$(echo "$CANCELED" | jq '. | length')

echo "📊 Clusters to delete:"
echo "   Failed: $FAILED_COUNT"
echo "   Canceled: $CANCELED_COUNT"
echo "   Total: $((FAILED_COUNT + CANCELED_COUNT))"
echo ""

if [ "$FAILED_COUNT" -eq 0 ] && [ "$CANCELED_COUNT" -eq 0 ]; then
  echo "✅ No clusters to delete"
  exit 0
fi

# Delete all failed clusters in parallel
if [ "$FAILED_COUNT" -gt 0 ]; then
  echo "🗑️  Deleting $FAILED_COUNT failed clusters in parallel..."
  echo "$FAILED" | jq -r '.[] | "\(.rg)|\(.name)"' | while IFS='|' read -r rg name; do
    (
      echo "  Deleting: $name (RG: $rg)"
      az aks delete --resource-group "$rg" --name "$name" --subscription "$SUBSCRIPTION_ID" --yes --no-wait >/dev/null 2>&1
      echo "  ✅ Deletion initiated: $name"
    ) &
  done
  wait
  echo ""
fi

# Delete all canceled clusters in parallel
if [ "$CANCELED_COUNT" -gt 0 ]; then
  echo "🗑️  Deleting $CANCELED_COUNT canceled clusters in parallel..."
  echo "$CANCELED" | jq -r '.[] | "\(.rg)|\(.name)"' | while IFS='|' read -r rg name; do
    (
      echo "  Deleting: $name (RG: $rg)"
      az aks delete --resource-group "$rg" --name "$name" --subscription "$SUBSCRIPTION_ID" --yes --no-wait >/dev/null 2>&1
      echo "  ✅ Deletion initiated: $name"
    ) &
  done
  wait
  echo ""
fi

echo "✅ All deletion requests initiated"
echo ""
echo "⏳ Waiting for deletions to complete (this may take 5-15 minutes)..."
echo ""

# Wait for all deletions to complete
TOTAL=$((FAILED_COUNT + CANCELED_COUNT))
DELETING=1
ITERATION=0

while [ "$DELETING" -gt 0 ]; do
  ITERATION=$((ITERATION + 1))
  
  # Count clusters still in deleting or failed/canceled state
  DELETING=$(az aks list --subscription "$SUBSCRIPTION_ID" \
    --query "[?contains(name, 'az-p-') && (provisioningState == 'Deleting' || provisioningState == 'Failed' || provisioningState == 'Canceled')].name" -o tsv 2>/dev/null | wc -l)
  
  if [ "$DELETING" -gt 0 ]; then
    echo "  [Iteration $ITERATION] Still deleting: $DELETING clusters remaining..."
    sleep 15
  fi
done

echo ""
echo "✅ All clusters deleted successfully!"
echo ""
echo "📊 Final Status:"
az aks list --subscription "$SUBSCRIPTION_ID" \
  --query "[?contains(name, 'az-p-')].{name:name, state:provisioningState}" -o table 2>/dev/null
