#!/usr/bin/env bash
# Import existing AKS clusters into Terraform state
# This fixes the "already exists" errors

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/../lib/init.sh"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
# Load .env via dotenv (RPC CR/LF trim). Fallback: raw source.
if [[ -f "$SCRIPT_DIR/../lib/deployment/dotenv.sh" ]]; then
  # shellcheck disable=SC1090
  source "$SCRIPT_DIR/../lib/deployment/dotenv.sh"
  load_deployment_env --repo-root "${PROJECT_ROOT:-$REPO_ROOT}"
elif [[ -n "${PROJECT_ROOT:-}" && -f "$PROJECT_ROOT/.env" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$PROJECT_ROOT/.env"
  set +a
elif [[ -n "${REPO_ROOT:-}" && -f "$REPO_ROOT/.env" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$REPO_ROOT/.env"
  set +a
fi
TERRAFORM_DIR="$PROJECT_ROOT/terraform/well-architected/cloud-sovereignty"

cd "$TERRAFORM_DIR"

echo "=== Importing Existing AKS Clusters into Terraform State ==="

# Get all existing clusters
CLUSTERS=$(az aks list --subscription fc08d829-4f14-413d-ab27-ce024425db0b --query "[?contains(name, 'az-p-')].{name:name, rg:resourceGroup}" -o json)

echo "Found $(echo "$CLUSTERS" | jq '. | length') existing clusters"

# Import each cluster
echo "$CLUSTERS" | jq -r '.[] | "\(.rg)|\(.name)"' | while IFS='|' read -r rg name; do
  # Extract region code from name (supports both old 2-char and new 3-char codes)
  region_code=$(echo "$name" | sed 's/az-p-\([a-z]*\)-aks-main/\1/')
  
  # Map region codes to full region names (supports both old and new codes)
  case "$region_code" in
    # New 3-character codes (standard)
    "nor") region="northeurope" ;;
    "wst") region="westeurope" ;;
    "frc") region="francecentral" ;;
    "swn") region="switzerlandnorth" ;;
    "swt") region="switzerlandwest" ;;
    "ita") region="italynorth" ;;
    "pol") region="polandcentral" ;;
    "spa") region="spaincentral" ;;
    "bel") region="belgiumcentral" ;;
    "aut") region="austriaeast" ;;
    "aus") region="australiaeast" ;;
    "eas") region="eastasia" ;;
    "cin") region="centralindia" ;;
    "sin") region="southindia" ;;
    "win") region="westindia" ;;
    "jpe") region="japaneast" ;;
    "jpw") region="japanwest" ;;
    "kor") region="koreacentral" ;;
    "kos") region="koreasouth" ;;
    "nzl") region="newzealandnorth" ;;
    "idn") region="indonesiacentral" ;;
    "mys") region="malaysiawest" ;;
    "uae") region="uaenorth" ;;
    "qat") region="qatarcentral" ;;
    "can") region="canadacentral" ;;
    "cae") region="canadaeast" ;;
    "bra") region="brazilsouth" ;;
    "chl") region="chilecentral" ;;
    "mex") region="mexicocentral" ;;
    "zaf") region="southafricanorth" ;;
    # Old 2-3 character codes (for backward compatibility with existing resources)
    "ne") region="northeurope" ;;
    "we") region="westeurope" ;;
    "uks") region="uksouth" ;;
    "ukw") region="ukwest" ;;
    "fc") region="francecentral" ;;
    "gwc") region="germanywestcentral" ;;
    "sn") region="switzerlandnorth" ;;
    "sw") region="switzerlandwest" ;;
    "in") region="italynorth" ;;
    "noe") region="norwayeast" ;;
    "pc") region="polandcentral" ;;
    "sc") region="spaincentral" ;;
    "swc") region="swedencentral" ;;
    "bc") region="belgiumcentral" ;;
    "ae") region="australiaeast" ;;  # Note: conflicts with austriaeast (old), prefer australiaeast
    "ase") region="australiasoutheast" ;;
    "ea") region="eastasia" ;;
    "sea") region="southeastasia" ;;
    "ci") region="centralindia" ;;
    "si") region="southindia" ;;
    "wi") region="westindia" ;;
    "je") region="japaneast" ;;
    "jw") region="japanwest" ;;
    "kc") region="koreacentral" ;;
    "ks") region="koreasouth" ;;
    "cc") region="canadacentral" ;;
    "ce") region="canadaeast" ;;
    "mc") region="mexicocentral" ;;
    "qc") region="qatarcentral" ;;
    "ilc") region="israelcentral" ;;
    "ic") region="indonesiacentral" ;;
    "mw") region="malaysiawest" ;;
    "nzn") region="newzealandnorth" ;;
    "san") region="southafricanorth" ;;
    "uan") region="uaenorth" ;;
    "bs") region="brazilsouth" ;;
    "chc") region="chilecentral" ;;
    *) echo "Unknown region code: $region_code"; continue ;;
  esac
  
  echo "Importing $name ($region)..."
  terraform import "module.region_deployment[\"$region\"].azurerm_kubernetes_cluster.main[0]" "/subscriptions/fc08d829-4f14-413d-ab27-ce024425db0b/resourceGroups/$rg/providers/Microsoft.ContainerService/managedClusters/$name" 2>&1 | grep -v "Warning\|Deprecated" || echo "  ⚠️  Import failed or already in state"
done

echo "=== ✅ Import Complete ==="
