# audit-logger.ps1 -- PostToolUse hook
# Logs every tool call to a structured audit log.
# Never blocks (always exits 0). Audit trail for compliance.
#
# Part of @connexum/ai-governance

$rawInput = [Console]::In.ReadToEnd()

if ([string]::IsNullOrWhiteSpace($rawInput)) { exit 0 }

try { $input_obj = $rawInput | ConvertFrom-Json } catch { exit 0 }

$toolName = if ($input_obj.tool_name) { $input_obj.tool_name } else { 'unknown' }
$agentName = if ($input_obj.agent_name) { $input_obj.agent_name } else { 'unknown' }
$toolInput = $input_obj.tool_input
$toolResult = if ($input_obj.tool_result) { $input_obj.tool_result.ToString().Substring(0, [Math]::Min(200, $input_obj.tool_result.ToString().Length)) } else { '' }

$timestamp = [DateTime]::UtcNow.ToString('yyyy-MM-ddTHH:mm:ssZ')
$sessionId = if ($env:CXNI_SESSION_ID) { $env:CXNI_SESSION_ID } else { [DateTimeOffset]::UtcNow.ToUnixTimeSeconds().ToString() }

# Determine audit log location
$auditDir = $null
foreach ($candidate in @(
    '.claude/governance/audit',
    '.claude/audit',
    'GOVERNANCE/audit'
)) {
    if (Test-Path $candidate) {
        $auditDir = $candidate
        break
    }
    try {
        New-Item -ItemType Directory -Path $candidate -Force | Out-Null
        $auditDir = $candidate
        break
    } catch { continue }
}

if (-not $auditDir) {
    $auditDir = '.claude/governance/audit'
    try { New-Item -ItemType Directory -Path $auditDir -Force | Out-Null } catch { exit 0 }
}

$auditFile = Join-Path $auditDir "audit-$([DateTime]::UtcNow.ToString('yyyy-MM-dd')).jsonl"

# Extract relevant details based on tool type
$target = switch ($toolName) {
    { $_ -in 'Edit', 'Write', 'NotebookEdit' } {
        if ($toolInput.file_path) { $toolInput.file_path } elseif ($toolInput.path) { $toolInput.path } else { 'unknown' }
    }
    'Bash' {
        $cmd = if ($toolInput.command) { $toolInput.command } else { 'unknown' }
        $cmd.Substring(0, [Math]::Min(100, $cmd.Length))
    }
    'Read' { if ($toolInput.file_path) { $toolInput.file_path } else { 'unknown' } }
    { $_ -in 'Glob', 'Grep' } { if ($toolInput.pattern) { $toolInput.pattern } else { 'unknown' } }
    'Agent' { if ($toolInput.description) { $toolInput.description } else { 'unknown' } }
    'WebSearch' { if ($toolInput.query) { $toolInput.query } else { 'unknown' } }
    'WebFetch' { if ($toolInput.url) { $toolInput.url } else { 'unknown' } }
    default { 'n/a' }
}

$entry = @{
    timestamp = $timestamp
    session = $sessionId
    agent = $agentName
    tool = $toolName
    target = $target
} | ConvertTo-Json -Compress

try {
    Add-Content -Path $auditFile -Value $entry -ErrorAction SilentlyContinue
} catch { }

exit 0
