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

$ErrorActionPreference = "Stop"
$stamp = Get-Date -Format "yyyyMMdd_HHmmss"
$root = Join-Path $PSScriptRoot ".."
$outDir = Join-Path $root "$EvidenceDir\E22_H1066_$stamp"
New-Item -ItemType Directory -Force -Path $outDir | Out-Null

$qaUrl = "$BaseUrl/public/executive-action-governance-qa.php?hospital=$Hospital"
if ($WriteTest) {
    $encodedToken = [System.Uri]::EscapeDataString($Token)
    $qaUrl += "&write_test=1&token=$encodedToken"
}
$storageUrl = "$BaseUrl/public/executive-action-governance-storage-check.php?hospital=$Hospital"
$dashboardUrl = "$BaseUrl/public/index.php?page=action-governance-dashboard&lang=en"
$actionCenterUrl = "$BaseUrl/public/index.php?page=action-center&lang=en"

Write-Host "Phase 10.6.6 - Governance, Ownership and Follow-up QA" -ForegroundColor Cyan
Write-Host "Hospital: $Hospital"
Write-Host "Write test: $($WriteTest.IsPresent)"
Write-Host "QA URL: $qaUrl"

try {
    $qa = Invoke-WebRequest -UseBasicParsing -Uri $qaUrl -TimeoutSec 90
    $qa.Content | Set-Content -Encoding UTF8 (Join-Path $outDir "governance_qa.txt")

    $storage = Invoke-WebRequest -UseBasicParsing -Uri $storageUrl -TimeoutSec 60
    $storage.Content | Set-Content -Encoding UTF8 (Join-Path $outDir "governance_storage_check.txt")

    $dashboard = Invoke-WebRequest -UseBasicParsing -Uri $dashboardUrl -TimeoutSec 90
    $dashboard.Content | Set-Content -Encoding UTF8 (Join-Path $outDir "governance_dashboard.html")

    $actionCenter = Invoke-WebRequest -UseBasicParsing -Uri $actionCenterUrl -TimeoutSec 90
    $actionCenter.Content | Set-Content -Encoding UTF8 (Join-Path $outDir "action_center.html")

    $qaLines = $qa.Content -split "`r?`n"
    $failCount = @($qaLines | Where-Object { $_ -match '^\[FAIL\]' }).Count
    $passCount = @($qaLines | Where-Object { $_ -match '^\[PASS\]' }).Count

    $summary = @()
    $summary += "Phase: 10.6.6"
    $summary += "Hospital: $Hospital"
    $summary += "Write test: $($WriteTest.IsPresent)"
    $summary += "QA HTTP: $($qa.StatusCode)"
    $summary += "Storage HTTP: $($storage.StatusCode)"
    $summary += "Governance dashboard HTTP: $($dashboard.StatusCode)"
    $summary += "Action Center HTTP: $($actionCenter.StatusCode)"
    $summary += "QA PASS lines: $passCount"
    $summary += "QA FAIL lines: $failCount"
    $summary | Set-Content -Encoding UTF8 (Join-Path $outDir "summary.txt")

    $zip = Join-Path $root "$EvidenceDir\evidence_E22_H1066_$stamp.zip"
    Compress-Archive -Path "$outDir\*" -DestinationPath $zip -Force

    Write-Host "Evidence: $zip" -ForegroundColor Green
    Write-Host "QA PASS lines: $passCount"
    Write-Host "QA FAIL lines: $failCount"

    if (
        $failCount -gt 0 -or
        $qa.StatusCode -ne 200 -or
        $storage.StatusCode -ne 200 -or
        $dashboard.StatusCode -ne 200 -or
        $actionCenter.StatusCode -ne 200
    ) {
        Write-Host "Result: FAIL" -ForegroundColor Red
        exit 1
    }

    Write-Host "Result: PASS" -ForegroundColor Green
    exit 0
}
catch {
    $errorText = $_ | Out-String
    $errorText | Set-Content -Encoding UTF8 (Join-Path $outDir "error.txt")
    Write-Host "Result: ERROR" -ForegroundColor Red
    Write-Host $errorText -ForegroundColor Red
    exit 2
}
