#!/usr/bin/env bash

# Check Key Vault deployment status
# REFACTORED - Uses common libraries

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/../lib/init.sh"

# Initialize
SUBSCRIPTION_ID="$(get_subscription_id)"
ensure_azure_cli || exit 1
set_subscription "$SUBSCRIPTION_ID" || true

log_section "CHECKING KEY VAULT DEPLOYMENT STATUS (36 REGIONS)"

log_info "Subscription: $SUBSCRIPTION_ID"
echo ""

# Expected Key Vault naming pattern: az-p-{region_code}-kv-secrets-001 (with dashes)
# Region codes are standardized to exactly 3 characters
# This matches Resource Group naming: az-p-{code}-rg-sec-001
# Some existing Key Vaults may use: azp{code}kvsecrets001 (legacy, no dashes, old codes)
REGIONS=($(get_all_regions))

log_subsection "KEY VAULT STATUS BY REGION"

EXISTING_COUNT=0
MISSING_COUNT=0
MISSING_REGIONS=()

for region_info in "${REGIONS[@]}"; do
    REGION_NAME="${region_info%%:*}"
    REGION_CODE="${region_info##*:}"
    
    # Use library function if available, otherwise extract from string
    if [ -z "$REGION_CODE" ]; then
        REGION_CODE=$(get_region_code "$REGION_NAME")
    fi
    
    # Try both naming patterns (standard with dashes, legacy without)
    KV_NAME_STANDARD="az-p-${REGION_CODE}-kv-secrets-001"  # Standard (with dashes, 3-char code, matches RG)
    KV_NAME_LEGACY="azp${REGION_CODE}kvsecrets001"  # Legacy (no dashes, may use old codes)
    KV_FOUND=""
    KV_NAME=""
    
    # Prefer standard naming, but check legacy if standard not found
    if az keyvault show --name "$KV_NAME_STANDARD" --query id &> /dev/null; then
        KV_FOUND="$KV_NAME_STANDARD"
        KV_NAME="$KV_NAME_STANDARD"
    elif az keyvault show --name "$KV_NAME_LEGACY" --query id &> /dev/null; then
        KV_FOUND="$KV_NAME_LEGACY"
        KV_NAME="$KV_NAME_LEGACY"
    fi
    
    if [ -n "$KV_FOUND" ]; then
        RG=$(az keyvault show --name "$KV_NAME" --query resourceGroup -o tsv 2>/dev/null)
        echo "✅ $REGION_NAME: $KV_NAME (RG: $RG)"
        ((EXISTING_COUNT++))
    else
        echo "❌ $REGION_NAME: $KV_NAME_STANDARD or $KV_NAME_LEGACY (NOT FOUND)"
        ((MISSING_COUNT++))
        MISSING_REGIONS+=("$REGION_NAME:$REGION_CODE")
    fi
done

echo ""
echo "=" | awk '{printf "%-64s\n", ""}'
echo "📊 SUMMARY"
echo "=" | awk '{printf "%-64s\n", ""}'
echo ""

echo "Existing Key Vaults: $EXISTING_COUNT/36"
echo "Missing Key Vaults: $MISSING_COUNT/36"
echo ""

if [ $MISSING_COUNT -gt 0 ]; then
    echo "Missing regions:"
    for region_info in "${MISSING_REGIONS[@]}"; do
        echo "  • ${region_info%%:*}"
    done
    echo ""
    echo "⚠️  Key Vaults need to be deployed via Terraform"
    exit 1
else
    echo "✅ All Key Vaults are deployed"
    exit 0
fi

