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

$ErrorActionPreference = "Stop"

if ([string]::IsNullOrWhiteSpace($OutDir)) {
  $stamp = Get-Date -Format "yyyyMMdd_HHmmss"
  $OutDir = Join-Path (Get-Location) "evidence_E15_H1063_$stamp"
}
New-Item -ItemType Directory -Force -Path $OutDir | Out-Null

$base = $BaseUrl.TrimEnd('/')
$qaUrl = "$base/public/executive-action-review-workflow-qa.php?hospital=$Hospital"
if ($WriteTest) {
  if ([string]::IsNullOrWhiteSpace($Token)) {
    throw "WriteTest requires -Token. Set EXEC_ACTION_REVIEW_QA_TOKEN or EXECUTIVE_REFRESH_TOKEN in .env and pass the same value here."
  }
  $qaUrl = "$qaUrl&write_test=1&token=$([uri]::EscapeDataString($Token))"
}

$storageUrl = "$base/public/executive-action-review-storage-check.php?hospital=$Hospital"
$workflowUrl = "$base/public/executive-action-review-check.php?hospital=$Hospital"

Write-Host "Phase 10.6.3 Review Workflow QA"
Write-Host "Hospital:" $Hospital
Write-Host "Output:" $OutDir
Write-Host ""

$targets = @(
  @{ Name = "01_storage_check.txt"; Url = $storageUrl },
  @{ Name = "02_workflow_check.txt"; Url = $workflowUrl },
  @{ Name = "03_workflow_qa.txt"; Url = $qaUrl }
)

foreach ($target in $targets) {
  Write-Host "GET" $target.Url
  $path = Join-Path $OutDir $target.Name
  try {
    $response = Invoke-WebRequest -UseBasicParsing -Uri $target.Url -TimeoutSec 120
    $response.Content | Out-File -FilePath $path -Encoding UTF8
    Write-Host "Saved" $path
  } catch {
    ("ERROR: " + $_.Exception.Message) | Out-File -FilePath $path -Encoding UTF8
    Write-Host "Failed" $path
  }
}

$summary = Join-Path $OutDir "00_README.txt"
@"
Phase 10.6.3 Review Workflow QA Evidence
Hospital: $Hospital
BaseUrl: $base
WriteTest: $WriteTest

Files:
- 01_storage_check.txt: Oracle storage/table/audit status.
- 02_workflow_check.txt: current worklist and latest audit rows.
- 03_workflow_qa.txt: PASS/PENDING gates and optional write proof result.

Expected after one UI save or WriteTest:
- active_storage_is_oracle = PASS
- main_table_found = PASS
- audit_table_found = PASS
- worklist_has_actions = PASS
- audit_rows_exist_for_day = PASS
- selected_action_audit_history = PASS
"@ | Out-File -FilePath $summary -Encoding UTF8

Write-Host ""
Write-Host "Done. Evidence folder:" $OutDir
