#!/usr/bin/env bash
# audit-dir-picker.sh -- Vendor-neutral audit directory selection.
#
# Source this file then call pick_audit_dir; the picked path is
# echoed to stdout. Caller captures it:
#   AUDIT_DIR=$(pick_audit_dir)
#
# Selection order (highest to lowest priority):
#   1. CXNI_AUDIT_DIR env var (operator override; always wins).
#   2. Active-IDE detection: scan CWD for IDE marker dirs in
#      preference order. First match wins. Each maps to its
#      conventional dir under the IDE namespace.
#        .claude/    -> .claude/governance/audit/    (Claude Code)
#        .cursor/    -> .cursor/governance/audit/    (Cursor)
#        .continue/  -> .continue/governance/audit/  (Continue)
#        .cody/      -> .cody/governance/audit/      (Sourcegraph Cody)
#        .aider/     -> .aider/governance/audit/     (Aider)
#        .gemini/    -> .gemini/governance/audit/    (Gemini Code Assist)
#   3. Vendor-neutral fallback: .governance/audit/
#   4. Legacy alias: GOVERNANCE/audit/ (only if it already exists,
#      so existing customers do not lose their history; new installs
#      never get this).
#
# F-NEW-CRIT-39g foundation: closes the Claude-Code-specific lock-in
# in audit-logger.sh / file-boundary-guard.sh / destructive-command-
# guard.sh so non-Claude IDEs can install governance without a
# stray .claude/ dir polluting their project.
#
# @connexum/ai-governance F-NEW-CRIT-39g

# IDE marker dirs in preference order. First match in CWD wins.
# Order rationale: Claude Code first because it is the most-deployed
# adapter today; the rest in alphabetical order so the choice is
# predictable when multiple IDE markers are present.
_CXNI_IDE_MARKERS=(
  ".claude"
  ".cursor"
  ".continue"
  ".cody"
  ".aider"
  ".gemini"
)

pick_audit_dir() {
  # 1. Operator override.
  if [ -n "${CXNI_AUDIT_DIR:-}" ]; then
    printf '%s\n' "$CXNI_AUDIT_DIR"
    return 0
  fi

  # 2. Active-IDE detection.
  local marker
  for marker in "${_CXNI_IDE_MARKERS[@]}"; do
    if [ -d "$marker" ]; then
      printf '%s/governance/audit\n' "$marker"
      return 0
    fi
  done

  # 4. Legacy alias: only if it already has content. Prevents new
  # installs from creating GOVERNANCE/ while letting existing customers
  # keep writing to it.
  if [ -d "GOVERNANCE/audit" ]; then
    printf 'GOVERNANCE/audit\n'
    return 0
  fi

  # 3. Vendor-neutral fallback.
  printf '.governance/audit\n'
}
