#!/usr/bin/env bash
# Fix cluster state by deleting failed/canceled clusters and recreating them
# This resolves import issues with clusters in bad states

set -e

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

echo "=== Fixing Cluster State ==="
echo ""
echo "This will delete failed/canceled clusters so Terraform can recreate them"
echo ""

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

CLUSTER_COUNT=$(echo "$FAILED_CLUSTERS" | jq '. | length')
echo "Found $CLUSTER_COUNT failed/canceled clusters"
echo ""

if [ "$CLUSTER_COUNT" -eq 0 ]; then
  echo "✅ No failed/canceled clusters found"
  exit 0
fi

echo "Deleting failed/canceled clusters..."
echo ""

echo "$FAILED_CLUSTERS" | jq -r '.[] | "\(.rg)|\(.name)|\(.state)"' | while IFS='|' read -r rg name state; do
  echo "Deleting $name ($state) in $rg..."
  az aks delete --name "$name" --resource-group "$rg" --subscription "$SUBSCRIPTION_ID" --yes --no-wait 2>&1 | grep -E "Deleted|Deleting|Error" || echo "  ⚠️  Delete initiated"
done

echo ""
echo "=== ✅ Delete Initiated ==="
echo ""
echo "Clusters are being deleted in the background."
echo "Wait 5-10 minutes, then re-run Terraform deployment."
