#!/usr/bin/env bash
# seed-keyvault.sh — Populate Azure Key Vault with all LysnrAI secrets.
#
# Prerequisites:
#   1. az login
#   2. A .env file with all secret values (or set them as env vars)
#
# Usage:
#   ./scripts/seed-keyvault.sh                          # uses default vault
#   AZURE_KEYVAULT_URL=https://kv-mywisprai.vault.azure.net ./scripts/seed-keyvault.sh
#
set -euo pipefail

VAULT_NAME="${AZURE_KEYVAULT_NAME:-kv-mywisprai}"

# Load .env if present
if [ -f .env ]; then
  set -a; source .env; set +a
fi

echo "🔐 Seeding Azure Key Vault: $VAULT_NAME"
echo ""

# Map: KV secret name → env var name
declare -A SECRETS=(
  ["lysnr-cosmos-endpoint"]="COSMOS_ENDPOINT"
  ["lysnr-cosmos-key"]="COSMOS_KEY"
  ["lysnr-jwt-secret"]="JWT_SECRET"
  ["lysnr-stripe-secret-key"]="STRIPE_SECRET_KEY"
  ["lysnr-stripe-webhook-secret"]="STRIPE_WEBHOOK_SECRET"
  ["lysnr-billing-internal-key"]="BILLING_INTERNAL_KEY"
  ["lysnr-blob-connection-string"]="AZURE_BLOB_CONNECTION_STRING"
  ["lysnr-blob-account-key"]="AZURE_BLOB_ACCOUNT_KEY"
  ["lysnr-gemini-api-key"]="GEMINI_API_KEY"
  ["lysnr-seed-secret"]="SEED_SECRET"
  ["lysnr-azure-speech-key"]="AZURE_SPEECH_KEY"
  ["lysnr-azure-openai-key"]="AZURE_OPENAI_KEY"
  ["lysnr-azure-openai-endpoint"]="AZURE_OPENAI_ENDPOINT"
)

ok=0
skip=0
fail=0

for kv_name in "${!SECRETS[@]}"; do
  env_var="${SECRETS[$kv_name]}"
  value="${!env_var:-}"

  if [ -z "$value" ]; then
    echo "  ⚠️  SKIP  $kv_name ($env_var not set)"
    ((skip++))
    continue
  fi

  if az keyvault secret set \
    --vault-name "$VAULT_NAME" \
    --name "$kv_name" \
    --value "$value" \
    --output none 2>/dev/null; then
    echo "  ✅  SET   $kv_name"
    ((ok++))
  else
    echo "  ❌  FAIL  $kv_name"
    ((fail++))
  fi
done

echo ""
echo "Done: $ok set, $skip skipped, $fail failed"
