param(
    [Parameter(Mandatory=$true)][string]$Executable,
    [Parameter(Mandatory=$true)][ValidateSet('manifest','determinism','audio-equivalence','quick')][string]$Test,
    [Parameter(Mandatory=$true)][string]$OutputRoot,
    [string]$ReferenceRoot='',
    [ValidateSet('Debug','Release')][string]$Configuration='Release'
)
$ErrorActionPreference='Stop'
. (Join-Path $PSScriptRoot 'CPUReportIO.ps1')
$output=Join-Path $OutputRoot ($Test+'-'+[DateTime]::UtcNow.ToString('yyyyMMddTHHmmssfffZ')+'-'+[guid]::NewGuid().ToString('N'))
$arguments=@('--self-test',$Test,'--output',$output)
if($Test -eq 'audio-equivalence'){
    if([string]::IsNullOrWhiteSpace($ReferenceRoot)){throw 'External S/R25 audio reference is required; candidate-generated reference is not an acceptance substitute'}
    $arguments+=@('--reference',(Join-Path $ReferenceRoot $Configuration))
}
& $Executable @arguments
if($LASTEXITCODE -ne 0){exit $LASTEXITCODE}
if($Test -eq 'manifest'){
    foreach($bad in @(@('--not-an-option','1'),@('--case','missing','--list'),@('--reference',(Join-Path $output 'missing-reference')))){
        & $Executable @bad
        if($LASTEXITCODE -eq 0){throw 'Invalid CLI or missing reference incorrectly passed'}
    }
    foreach($kind in @('schema','configuration','digest')){
        $metadata=@{schema='DeepPluck-CPU-Provenance-Rev1';configuration=$Configuration;
            requestedManifest='DeepPluck-CPU-0.11.5-Rev1';source_sha256=('a'*64);environment_sha256=('b'*64)}
        switch($kind){
            'schema' {$metadata.schema='invalid-synthetic-schema'}
            'configuration' {$metadata.configuration=if($Configuration -eq 'Debug'){'Release'}else{'Debug'}}
            'digest' {$metadata.source_sha256='invalid-digest'}
        }
        $metadataFile=Join-Path $output "invalid-metadata-$kind.json"
        $metadata | ConvertTo-Json | Set-Content -LiteralPath $metadataFile -Encoding utf8
        & $Executable --suite quick --mode audio --metadata $metadataFile --output (Join-Path $output "invalid-metadata-$kind-run")
        if($LASTEXITCODE -eq 0){throw "Invalid metadata incorrectly passed: $kind"}
    }
    & (Join-Path $PSScriptRoot 'TestCPUAnalysis.ps1') -Executable $Executable -OutputRoot $output
    & (Join-Path $PSScriptRoot 'TestCPUToneComparison.ps1') -OutputRoot $output
    & (Join-Path $PSScriptRoot 'ExportCPUListeningWave.ps1') -SelfTest -Output (Join-Path $output ('wave-unit-'+[guid]::NewGuid().ToString('N').Substring(0,8)))
    if($LASTEXITCODE -ne 0){throw 'Float32 listening export self-test failed'}
}
exit 0
