#!/usr/bin/env bash

_sync_service_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

  bw config server "$BW_SERVER_URL" >/dev/null 2>&1

  local target_file="$AUTO_SCRIPTS_DIR/service.env"
  mkdir -p "$(dirname "$target_file")"
  touch "$target_file"
  chmod 600 "$target_file"

  # Unlock si pas de session active
  if [ -z "${BW_SESSION:-}" ]; then
    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
    BW_SESSION=$(BW_MASTER_PASSWORD="$BW_MASTER_PASSWORD" bw unlock --passwordenv BW_MASTER_PASSWORD --raw 2>/dev/null)
    if [ -z "$BW_SESSION" ]; then
      echo "Échec du déverrouillage Bitwarden." >&2
      return 1
    fi
    export BW_SESSION
  fi

  echo "Sync des secrets de service..." >&2

  # Récupérer l'id du dossier "services"
  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']=='services'), ''))")

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

  # Extraire TITRE=password pour chaque item dont le nom est une var d'env valide
  local rendered_lines
  rendered_lines=$(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 "$rendered_lines" ]; then
    echo "Aucun secret de service chargé." >&2
    return 1
  fi

  local loaded
  loaded=$(printf '%s' "$rendered_lines" | grep -c '.')

  printf '%s\n' "$rendered_lines" > "$target_file"
  chmod 600 "$target_file"

  echo "Secrets de service écrits dans : $target_file"
  echo "Secrets de service chargés : $loaded"
}

_sync_service_secrets
unset -f _sync_service_secrets
