# token-tracker.ps1 -- PostToolUse hook (matcher: Agent)
# Records token usage per Agent tool call for anomaly detection baselines.
# Never blocks (always exits 0).
#
# 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 { '' }

# Only track Agent calls (which consume API tokens)
if ($toolName -ne 'Agent') { exit 0 }

$agentName = if ($input_obj.agent_name) { $input_obj.agent_name } else { 'unknown' }
$timestamp = [DateTime]::UtcNow.ToString('yyyy-MM-ddTHH:mm:ssZ')

# Extract usage from tool result if available
$toolResult = if ($input_obj.tool_result) { $input_obj.tool_result.ToString() } else { '' }
$totalTokens = 0
$durationMs = 0

if ($toolResult -match 'total_tokens:\s*(\d+)') { $totalTokens = [int]$Matches[1] }
if ($toolResult -match 'duration_ms:\s*(\d+)') { $durationMs = [int]$Matches[1] }

# Token tracking directory
$trackDir = $null
foreach ($candidate in @(
    '.claude/governance/token-tracking',
    '.claude/cost-tracking',
    'GOVERNANCE/token-tracking'
)) {
    if (Test-Path $candidate) {
        $trackDir = $candidate
        break
    }
    try {
        New-Item -ItemType Directory -Path $candidate -Force | Out-Null
        $trackDir = $candidate
        break
    } catch { continue }
}

if (-not $trackDir) { exit 0 }

$trackFile = Join-Path $trackDir "tokens-$([DateTime]::UtcNow.ToString('yyyy-MM-dd')).jsonl"

$entry = @{
    timestamp = $timestamp
    agent = $agentName
    tokens = $totalTokens
    duration_ms = $durationMs
} | ConvertTo-Json -Compress

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

# Update running session total for budget gate
$budgetFile = $null
foreach ($candidate in @(
    '.claude/governance/token-budget.json',
    '.claude/cost-tracking/budget.json'
)) {
    if (Test-Path $candidate) {
        $budgetFile = $candidate
        break
    }
}

if ($budgetFile -and $totalTokens -gt 0) {
    try {
        $budget = Get-Content $budgetFile -Raw | ConvertFrom-Json
        $current = if ($budget.current_session_tokens) { [int]$budget.current_session_tokens } else { 0 }
        $budget.current_session_tokens = $current + $totalTokens
        $budget | ConvertTo-Json | Set-Content $budgetFile
    } catch { }
}

exit 0
