# audit-dir-picker.ps1 -- Vendor-neutral audit directory selection.
#
# Dot-source this file then call Get-AuditDir; the picked path is
# returned to the pipeline. Caller captures it:
#   $auditDir = Get-AuditDir
#
# 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 the bash hooks so non-Claude IDEs on Windows can install
# governance without a stray .claude/ dir polluting their project.
#
# Mirrors src/hooks/audit-dir-picker.sh exactly (same selection
# order, same fallback chain). Tested by tests/powershell-hooks.test.ts
# parity assertion.
#
# @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.
$Script:CXNI_IDE_MARKERS = @(
    ".claude",
    ".cursor",
    ".continue",
    ".cody",
    ".aider",
    ".gemini"
)

function Get-AuditDir {
    [CmdletBinding()]
    param()

    # 1. Operator override.
    $override = $env:CXNI_AUDIT_DIR
    if ($override) {
        return $override
    }

    # 2. Active-IDE detection.
    foreach ($marker in $Script:CXNI_IDE_MARKERS) {
        if (Test-Path -Path $marker -PathType Container) {
            return "$marker/governance/audit"
        }
    }

    # 4. Legacy alias: only if it already has content. Prevents new
    # installs from creating GOVERNANCE/ while letting existing customers
    # keep writing to it.
    if (Test-Path -Path "GOVERNANCE/audit" -PathType Container) {
        return "GOVERNANCE/audit"
    }

    # 3. Vendor-neutral fallback.
    return ".governance/audit"
}
