param(
    [string]$BaseUrl = "http://localhost"
)

$ErrorActionPreference = "Stop"
$stamp = Get-Date -Format "yyyyMMdd_HHmmss"
$root = Split-Path -Parent $PSScriptRoot
$evidenceDir = Join-Path $root "storage\qa\E19_H106421_$stamp"
$zipPath = Join-Path $root "evidence_E19_H106421_$stamp.zip"
New-Item -ItemType Directory -Force -Path $evidenceDir | Out-Null

$url = "$($BaseUrl.TrimEnd('/'))/public/executive-action-review-sidebar-qa.php"
$resultFile = Join-Path $evidenceDir "sidebar_qa.txt"
$metaFile = Join-Path $evidenceDir "run_meta.txt"

"Phase=10.6.4.2.1" | Set-Content -Encoding UTF8 $metaFile
"RunAt=$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" | Add-Content -Encoding UTF8 $metaFile
"URL=$url" | Add-Content -Encoding UTF8 $metaFile

try {
    $response = Invoke-WebRequest -Uri $url -UseBasicParsing -TimeoutSec 60
    $response.Content | Set-Content -Encoding UTF8 $resultFile
    if ($response.StatusCode -ne 200 -or $response.Content -notmatch 'Result: PASS') {
        throw "QA gate did not return PASS."
    }
} catch {
    $_ | Out-String | Add-Content -Encoding UTF8 $metaFile
    throw
}

if (Test-Path $zipPath) { Remove-Item $zipPath -Force }
Compress-Archive -Path (Join-Path $evidenceDir '*') -DestinationPath $zipPath -Force
Write-Host "PASS - Phase 10.6.4.2.1 sidebar structure QA"
Write-Host "Evidence: $zipPath"
