# Long-poll hooks-approval for PermissionRequest decisions
# Reads hook stdin, POSTs to backend, waits up to 125s for UI response
# Returns hookSpecificOutput JSON per Claude Code PermissionRequest docs
param([string]$agent = "")
if ($agent) { $logFile = "$PSScriptRoot/../.claude-$agent/debug/hooks.log" }
else { $logFile = "$PSScriptRoot/../.claude/debug/hooks.log"; $agent = "local" }
$ts = Get-Date -Format "HH:mm:ss.fff"
$b = [Console]::In.ReadToEnd()
Add-Content $logFile "[$ts] [PERM] Hook fired for agent=$agent stdin_len=$($b.Length)"
try {
  $j = $b | ConvertFrom-Json
  Add-Content $logFile "[$ts] [PERM] tool=$($j.tool_name) session=$($j.session_id)"
} catch {
  Add-Content $logFile "[$ts] [PERM] WARN: stdin not valid JSON"
}
try {
  Add-Content $logFile "[$ts] [PERM] POSTing to backend..."
  $r = Invoke-RestMethod -Uri 'http://localhost:4101/api/hooks-approval/permission' -Method POST -Body $b -ContentType 'application/json' -TimeoutSec 125
  $ts2 = Get-Date -Format "HH:mm:ss.fff"
  if ($r -and $r.hookSpecificOutput) {
    $out = $r | ConvertTo-Json -Depth 10 -Compress
    Add-Content $logFile "[$ts2] [PERM] Got response: $out"
    $out
  } else {
    Add-Content $logFile "[$ts2] [PERM] Empty/timeout response (no hookSpecificOutput)"
  }
} catch {
  $ts2 = Get-Date -Format "HH:mm:ss.fff"
  Add-Content $logFile "[$ts2] [PERM] ERROR: $($_.Exception.Message)"
}
