#!/usr/bin/env bash

_sync_project_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 project_name
  project_name="$(basename "$PWD")"
  local target_file="$PWD/.env"

  echo "Projet détecté : $project_name" >&2

  # 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 "Récupération des secrets projet..." >&2

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

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

  # Chercher l'item dont le nom == project_name dans le dossier projects
  local notes
  notes=$(bw list items --folderid "$folder_id" --session "$BW_SESSION" 2>/dev/null \
    | python3 -c "
import sys, json

items = json.load(sys.stdin)
for item in items:
    if item.get('name') == '$project_name':
        print((item.get('notes') or '').strip())
        break
")

  if [ -z "$notes" ]; then
    echo "Aucune note trouvée pour '$project_name' dans Bitwarden." >&2
    return 1
  fi

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

  local loaded
  loaded=$(grep -c '.' "$target_file" || true)

  echo "Secrets écrits dans : $target_file"
  echo "Lignes écrites : $loaded"
}

_sync_project_secrets
unset -f _sync_project_secrets
