param(
    [string]$BaseUrl = "http://localhost",
    [string]$Hospital = "njch",
    [int]$Days = 30,
    [string]$EvidenceDir = "evidence"
)

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

$qaUrl = "$BaseUrl/public/executive-review-dashboard-purity-qa.php?hospital=$Hospital&days=$Days"
$productionUrl = "$BaseUrl/public/index.php?page=action-review-dashboard&lang=en&days=$Days"
$technicalUrl = "$BaseUrl/public/index.php?page=action-review-dashboard&lang=en&days=$Days&include_qa=1"

Write-Host "Phase 10.6.5.1 - Production Analytics Purity QA" -ForegroundColor Cyan
Write-Host "Hospital: $Hospital"
Write-Host "Analytics window: $Days days"
Write-Host "QA URL: $qaUrl"

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

    $production = Invoke-WebRequest -UseBasicParsing -Uri $productionUrl -TimeoutSec 60
    $production.Content | Set-Content -Encoding UTF8 (Join-Path $outDir "dashboard_production_only.html")

    $technical = Invoke-WebRequest -UseBasicParsing -Uri $technicalUrl -TimeoutSec 60
    $technical.Content | Set-Content -Encoding UTF8 (Join-Path $outDir "dashboard_with_qa_activity.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.5.1"
    $summary += "Hospital: $Hospital"
    $summary += "Days: $Days"
    $summary += "QA HTTP: $($qa.StatusCode)"
    $summary += "Production dashboard HTTP: $($production.StatusCode)"
    $summary += "Technical dashboard HTTP: $($technical.StatusCode)"
    $summary += "QA FAIL lines: $failCount"
    $summary += "QA PASS lines: $passCount"
    $summary += "Write operations: NONE"
    $summary | Set-Content -Encoding UTF8 (Join-Path $outDir "summary.txt")

    $zip = Join-Path $root "$EvidenceDir\evidence_E21_H10651_$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
        $production.StatusCode -ne 200 -or
        $technical.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
}
