# hook-wrapper.ps1 -- Universal wrapper that respects runtime controls
# Wraps any governance hook with profile checking and disable controls.
# Usage: pwsh hook-wrapper.ps1 <actual-hook.ps1>
#
# Environment variables:
#   CXNI_HOOK_PROFILE     - minimal|standard|strict (default: standard)
#   CXNI_DISABLED_HOOKS   - comma-separated list of hook names to skip
#   CXNI_MAINTENANCE_MODE - true to disable ALL blocking hooks (audit-only)
#
# Part of @connexum/ai-governance

param(
    [Parameter(Position = 0, Mandatory = $true)]
    [string]$HookScript
)

if (-not (Test-Path $HookScript)) { exit 0 }

$hookName = [System.IO.Path]::GetFileNameWithoutExtension($HookScript)

# Check if hook is explicitly disabled
if ($env:CXNI_DISABLED_HOOKS) {
    $disabled = $env:CXNI_DISABLED_HOOKS -split ',' | ForEach-Object { $_.Trim() }
    if ($hookName -in $disabled) { exit 0 }
}

# In maintenance mode, convert all blocking hooks to audit-only
if ($env:CXNI_MAINTENANCE_MODE -eq 'true') {
    $input_data = [Console]::In.ReadToEnd()
    try {
        $output = $input_data | pwsh -File $HookScript 2>&1
        foreach ($line in $output) {
            [Console]::Error.WriteLine("[MAINTENANCE] $line")
        }
    } catch { }
    exit 0
}

# Check profile-based activation
$profile = if ($env:CXNI_HOOK_PROFILE) { $env:CXNI_HOOK_PROFILE } else { 'standard' }

# Profile hierarchy: strict includes standard includes minimal
$hookProfiles = @{
    'governance-file-shield' = 'minimal'
    'secret-leak-scanner' = 'minimal'
    'destructive-command-guard' = 'minimal'
    'web-access-gate' = 'standard'
    'audit-logger' = 'standard'
    'file-boundary-guard' = 'strict'
    'cost-budget-gate' = 'strict'
    'token-tracker' = 'strict'
    'file-change-tracker' = 'strict'
    'governance-integrity-check' = 'minimal'
}

$requiredProfile = if ($hookProfiles.ContainsKey($hookName)) { $hookProfiles[$hookName] } else { 'standard' }

$profileRanks = @{ 'minimal' = 1; 'standard' = 2; 'strict' = 3 }
$profileRank = if ($profileRanks.ContainsKey($profile)) { $profileRanks[$profile] } else { 0 }
$requiredRank = if ($profileRanks.ContainsKey($requiredProfile)) { $profileRanks[$requiredProfile] } else { 0 }

if ($profileRank -lt $requiredRank) { exit 0 }

# Run the actual hook -- pass stdin through
$input_data = [Console]::In.ReadToEnd()
$input_data | pwsh -File $HookScript
exit $LASTEXITCODE
