#!/usr/bin/env bash

_load_global_secrets() {
  source "$LEADTECH/scripts/env_paths.sh" || { echo "env_paths.sh introuvable" >&2; return 1; }

  if ! command -v bw >/dev/null 2>&1; then
    echo "bw (Bitwarden CLI) introuvable" >&2
    return 1
  fi

  # Configurer le serveur si pas déjà fait
  bw config server "$BW_SERVER_URL" >/dev/null 2>&1

  # Demander le master password si pas en variable
  if [ -z "${BW_MASTER_PASSWORD:-}" ]; then
    printf "Master password Bitwarden : " >&2
    stty -echo
    IFS= read -r BW_MASTER_PASSWORD
    stty echo
    printf '\n' >&2
  fi

  # Unlock et récupérer le session token
  local session
  session=$(BW_MASTER_PASSWORD="$BW_MASTER_PASSWORD" bw unlock --passwordenv BW_MASTER_PASSWORD --raw 2>/dev/null)
  if [ -z "$session" ]; then
    echo "Échec du déverrouillage Bitwarden." >&2
    return 1
  fi
  export BW_SESSION="$session"

  echo "Chargement des secrets globaux..." >&2

  # Récupérer l'id du dossier "global"
  local folder_id
  folder_id=$(bw list folders --session "$BW_SESSION" 2>/dev/null \
    | python3 -c "import sys,json; folders=json.load(sys.stdin); print(next((f['id'] for f in folders if f['name']=='global'), ''))")

  if [ -z "$folder_id" ]; then
    echo "Dossier 'global' introuvable dans Bitwarden." >&2
    return 1
  fi

  # Lister les items du dossier et extraire TITRE=password
  local pairs
  pairs=$(bw list items --folderid "$folder_id" --session "$BW_SESSION" 2>/dev/null \
    | python3 -c "
import sys, json, re

items = json.load(sys.stdin)
for item in items:
    title = item.get('name', '')
    password = (item.get('login') or {}).get('password') or ''
    password = password.strip()
    if not re.match(r'^[A-Z_][A-Z0-9_]*$', title):
        continue
    if not password:
        continue
    print(title + '=' + password)
")

  if [ -z "$pairs" ]; then
    echo "Aucun secret global chargé." >&2
    return 1
  fi

  local loaded=0
  while IFS='=' read -r var_name value; do
    [ -z "$var_name" ] && continue
    export "$var_name=$value"
    loaded=$((loaded + 1))
  done <<< "$pairs"

  echo "Secrets chargés : $loaded"
}

_load_global_secrets
unset -f _load_global_secrets
