#!/usr/bin/env bash
# Import all existing resources into Terraform state
# Fixes "already exists" errors

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/../lib/init.sh"
SCRIPT_NAME="import-all-resources.sh"
SCRIPT_DESC="Import existing Azure resources into state; supports old/new region codes"
SCRIPT_USAGE="${SCRIPT_NAME} [--region <code>] [--dry-run] [--help]"
SCRIPT_OPTIONS="--region <code>    Region filter (3-char or legacy 2-char)\n--dry-run          Print import commands only\n--help             Show help"
SCRIPT_REQUIREMENTS="Azure CLI, Terraform (if using terraform import)"
handle_help "${1:-}"

DRY_RUN="${DRY_RUN:-0}"
run() {
  if [ "$DRY_RUN" = "1" ]; then
    echo "[DRY RUN] $*"; return 0
  fi
  "$@"
}

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 All Existing Resources ==="

# Region code mapping (supports both old 2-char and new 3-char codes for backward compatibility)
# Standard codes are now 3 characters, but we maintain old mappings for existing resources
declare -A REGION_CODES=(
  ["northeurope"]="nor"
  ["uksouth"]="uks"
  ["ukwest"]="ukw"
  ["westeurope"]="wst"
  ["francecentral"]="frc"
  ["germanywestcentral"]="gwc"
  ["switzerlandnorth"]="swn"
  ["switzerlandwest"]="swt"
  ["italynorth"]="ita"
  ["norwayeast"]="noe"
  ["polandcentral"]="pol"
  ["spaincentral"]="spa"
  ["swedencentral"]="swc"
  ["belgiumcentral"]="bel"
  ["austriaeast"]="aut"
  ["australiaeast"]="aus"
  ["australiasoutheast"]="ase"
  ["eastasia"]="eas"
  ["southeastasia"]="sea"
  ["centralindia"]="cin"
  ["southindia"]="sin"
  ["westindia"]="win"
  ["japaneast"]="jpe"
  ["japanwest"]="jpw"
  ["koreacentral"]="kor"
  ["koreasouth"]="kos"
  ["newzealandnorth"]="nzl"
  ["indonesiacentral"]="idn"
  ["malaysiawest"]="mys"
  ["uaenorth"]="uae"
  ["qatarcentral"]="qat"
  ["israelcentral"]="ilc"
  ["canadacentral"]="can"
  ["canadaeast"]="cae"
  ["brazilsouth"]="bra"
  ["chilecentral"]="chl"
  ["mexicocentral"]="mex"
  ["southafricanorth"]="zaf"
)

# Reverse mapping for old codes (for importing existing resources)
declare -A OLD_CODE_TO_REGION=(
  ["ne"]="northeurope"
  ["we"]="westeurope"
  ["fc"]="francecentral"
  ["sn"]="switzerlandnorth"
  ["sw"]="switzerlandwest"
  ["in"]="italynorth"
  ["pc"]="polandcentral"
  ["sc"]="spaincentral"
  ["bc"]="belgiumcentral"
  ["ae"]="australiaeast"  # Note: conflicts with austriaeast (old), prefer australiaeast
  ["ea"]="eastasia"
  ["ci"]="centralindia"
  ["si"]="southindia"
  ["wi"]="westindia"
  ["je"]="japaneast"
  ["jw"]="japanwest"
  ["kc"]="koreacentral"
  ["ks"]="koreasouth"
  ["cc"]="canadacentral"
  ["ce"]="canadaeast"
  ["bs"]="brazilsouth"
  ["mc"]="mexicocentral"
  ["qc"]="qatarcentral"
  ["ic"]="indonesiacentral"
  ["mw"]="malaysiawest"
  ["nzn"]="newzealandnorth"
  ["san"]="southafricanorth"
  ["uan"]="uaenorth"
  ["chc"]="chilecentral"
)

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

echo "Step 1: Importing West Europe Admin Resources"

# Import West Europe resource groups (using new 3-char code)
for rg_type in compute network storage security monitoring identity; do
  # Try new 3-char code first, fall back to old 2-char code
  rg_name_new="az-p-wst-rg-${rg_type}-001"
  rg_name_old="az-p-we-rg-${rg_type}-001"
  
  # Check which one exists
  if az group show --name "$rg_name_new" &> /dev/null; then
    rg_name="$rg_name_new"
  elif az group show --name "$rg_name_old" &> /dev/null; then
    rg_name="$rg_name_old"
  else
    echo "  ⚠️  Resource group not found: $rg_name_new or $rg_name_old"
    continue
  fi
  
  resource_id="/subscriptions/${SUBSCRIPTION_ID}/resourceGroups/${rg_name}"
  
  echo "Importing $rg_name..."
  run terraform import "module.admin_region[0].azurerm_resource_group.${rg_type}" "$resource_id" 2>&1 | grep -E "Import|Imported|Error" || echo "  ⚠️  Already in state or failed"
done

echo "Step 2: Importing Existing AKS Clusters"

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

# Import each cluster
echo "$CLUSTERS" | jq -r '.[] | "\(.rg)|\(.name)"' | while IFS='|' read -r rg name; do
  # Extract region code from name
  region_code=$(echo "$name" | sed 's/az-p-\([a-z]*\)-aks-main/\1/')
  
  # Find region name from code
  region=""
  for reg in "${!REGION_CODES[@]}"; do
    if [ "${REGION_CODES[$reg]}" == "$region_code" ]; then
      region="$reg"
      break
    fi
  done
  
  if [ -z "$region" ]; then
    echo "  ⚠️  Unknown region code: $region_code"
    continue
  fi
  
  echo "Importing $name ($region)..."
  resource_id="/subscriptions/${SUBSCRIPTION_ID}/resourceGroups/${rg}/providers/Microsoft.ContainerService/managedClusters/${name}"
  
  run terraform import "module.region_deployment[\"$region\"].azurerm_kubernetes_cluster.main[0]" "$resource_id" 2>&1 | grep -E "Import|Imported|Error" | tail -1 || echo "  ⚠️  Import failed or already in state"
done

echo "=== ✅ Import Complete ==="
echo "Next: Run terraform apply to continue deployment"
