param(
    [string]$BaseUrl = "http://localhost",
    [string]$Hospital = "njch",
    [string]$Action = "",
    [switch]$WriteTest,
    [string]$Token = ""
)

$ErrorActionPreference = "Stop"
$base = $BaseUrl.TrimEnd('/')
$query = "hospital=$([uri]::EscapeDataString($Hospital))"
if ($Action) {
    $query += "&action=$([uri]::EscapeDataString($Action))"
}
if ($WriteTest) {
    if (-not $Token) {
        throw "-WriteTest requires -Token. Set EXEC_ACTION_REVIEW_QA_TOKEN in .env and pass the same value."
    }
    $query += "&write_test=1&token=$([uri]::EscapeDataString($Token))"
}

$url = "$base/executive-action-review-management-qa.php?$query"
$stamp = Get-Date -Format "yyyyMMdd_HHmmss"
$evidenceDir = Join-Path $PSScriptRoot "evidence_E16_H1064_$stamp"
New-Item -ItemType Directory -Path $evidenceDir -Force | Out-Null

Write-Host "Running Phase 10.6.4 Review Management QA..." -ForegroundColor Cyan
$response = Invoke-WebRequest -Uri $url -UseBasicParsing
$content = [string]$response.Content

$responseFile = Join-Path $evidenceDir "review_management_qa.txt"
$content | Set-Content -Path $responseFile -Encoding UTF8

$meta = @(
    "Phase: 10.6.4",
    "Hospital: $Hospital",
    "BaseUrl: $base",
    "Action: $Action",
    "WriteTest: $($WriteTest.IsPresent)",
    "HTTP Status: $($response.StatusCode)",
    "ExecutedAt: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')"
)
$meta | Set-Content -Path (Join-Path $evidenceDir "run_metadata.txt") -Encoding UTF8

Write-Host ""
Write-Host $content

$failLines = @($content -split "`r?`n" | Where-Object { $_ -match '^\[FAIL\]' })
$errorLines = @($content -split "`r?`n" | Where-Object { $_ -match '^ERROR:' })

$zipPath = "$evidenceDir.zip"
Compress-Archive -Path (Join-Path $evidenceDir '*') -DestinationPath $zipPath -Force
Write-Host ""
Write-Host "Evidence: $zipPath" -ForegroundColor Green

if ($errorLines.Count -gt 0 -or $failLines.Count -gt 0) {
    Write-Host "QA FAILED. Review the FAIL/ERROR lines above." -ForegroundColor Red
    exit 1
}

Write-Host "QA completed without FAIL gates." -ForegroundColor Green
exit 0
