# hook-utils.ps1 -- Shared validation for all governance hooks.
#
# Dot-source this file at the top of every hook script:
#   . "$PSScriptRoot\hook-utils.ps1"
#
# Provides:
#   Read-HookInput  - Read and validate stdin JSON
#   $Script:HookInput     - Validated JSON object
#   $Script:HookToolName  - Extracted tool_name
#   $Script:HookToolInput - Extracted tool_input
#
# @connexum/ai-governance

$Script:MAX_INPUT_BYTES = 1048576

function Read-HookInput {
    # Read all stdin
    $rawInput = [Console]::In.ReadToEnd()

    # Check input size
    $inputSize = [System.Text.Encoding]::UTF8.GetByteCount($rawInput)
    if ($inputSize -gt $Script:MAX_INPUT_BYTES) {
        [Console]::Error.WriteLine("BLOCKED: Hook input exceeds maximum size ($inputSize bytes > $($Script:MAX_INPUT_BYTES) bytes). Possible injection attempt.")
        exit 2
    }

    # Check for empty input
    if ([string]::IsNullOrWhiteSpace($rawInput)) {
        exit 0
    }

    # Validate JSON structure
    try {
        $Script:HookInput = $rawInput | ConvertFrom-Json
    }
    catch {
        [Console]::Error.WriteLine("BLOCKED: Hook input is not valid JSON. Possible injection attempt.")
        exit 2
    }

    # Extract top-level fields
    $Script:HookToolName = if ($Script:HookInput.tool_name) { $Script:HookInput.tool_name } else { '' }
    $Script:HookToolInput = if ($Script:HookInput.tool_input) { $Script:HookInput.tool_input } else { '' }
}
