<#
.SYNOPSIS
    Meta-runner that invokes every per-phase Phase 6.x compliance script and
    reports an aggregate verdict.

.DESCRIPTION
    Runs phase-6-1-compliance.ps1, phase-6-2, phase-6-3, phase-6-4 in sequence.
    Each sub-script returns its own exit code; this wrapper aggregates them.
    Useful before a v2 release tag + as the `dotnet test` companion in CI.

.NOTES
    Usage:  pwsh ./scripts/compliance/phase-6-all.ps1
    Exit:   0 = every phase passed; 1 = one or more phases failed
#>
[CmdletBinding()]
param()

$ErrorActionPreference = 'Continue'

$phases = @(
    @{ Name = 'Phase 6.1 - Resilience & Observability'; Script = 'phase-6-1-compliance.ps1' },
    @{ Name = 'Phase 6.2 - Authorization runtime';       Script = 'phase-6-2-compliance.ps1' },
    @{ Name = 'Phase 6.3 - Redundancy runtime';          Script = 'phase-6-3-compliance.ps1' },
    @{ Name = 'Phase 6.4 - Admin UI completion';         Script = 'phase-6-4-compliance.ps1' }
)

$results = @()
$startedAt = Get-Date

foreach ($phase in $phases) {
    Write-Host ""
    Write-Host ""
    Write-Host "=============================================================" -ForegroundColor DarkGray
    Write-Host ("Running {0}" -f $phase.Name) -ForegroundColor Cyan
    Write-Host "=============================================================" -ForegroundColor DarkGray

    $scriptPath = Join-Path $PSScriptRoot $phase.Script
    if (-not (Test-Path $scriptPath)) {
        Write-Host ("  [MISSING] {0}" -f $phase.Script) -ForegroundColor Red
        $results += @{ Name = $phase.Name; Exit = 2 }
        continue
    }

    # Invoke each sub-script in its own powershell.exe process so its local
    # $ErrorActionPreference + exit-code semantics can't interfere with the meta-runner's
    # state. Slower (one process spawn per phase) but makes aggregate PASS/FAIL match
    # standalone runs exactly.
    & powershell.exe -NoProfile -ExecutionPolicy Bypass -File $scriptPath
    $exitCode = $LASTEXITCODE
    $results += @{ Name = $phase.Name; Exit = $exitCode }
}

$elapsed = (Get-Date) - $startedAt

Write-Host ""
Write-Host ""
Write-Host "=============================================================" -ForegroundColor DarkGray
Write-Host "Phase 6 compliance aggregate" -ForegroundColor Cyan
Write-Host "=============================================================" -ForegroundColor DarkGray

$totalFailures = 0
foreach ($r in $results) {
    $colour = if ($r.Exit -eq 0) { 'Green' } else { 'Red' }
    $tag    = if ($r.Exit -eq 0) { 'PASS' }     else { "FAIL (exit=$($r.Exit))" }
    Write-Host ("  [{0}] {1}" -f $tag, $r.Name) -ForegroundColor $colour
    if ($r.Exit -ne 0) { $totalFailures++ }
}

Write-Host ""
Write-Host ("Elapsed: {0:N1} s" -f $elapsed.TotalSeconds) -ForegroundColor DarkGray

if ($totalFailures -eq 0) {
    Write-Host "Phase 6 aggregate: PASS" -ForegroundColor Green
    exit 0
}
Write-Host ("Phase 6 aggregate: {0} phase(s) FAILED" -f $totalFailures) -ForegroundColor Red
exit 1
