param(
    [Parameter(Mandatory=$true)][string]$Root,
    [Parameter(Mandatory=$true)][string]$Report
)
$ErrorActionPreference='Stop'
. (Join-Path $PSScriptRoot 'CPUReportIO.ps1')
if(Test-Path -LiteralPath $Report){throw 'Verification evidence already exists'}
$run=Get-Content -LiteralPath (Join-Path $Root 'results.json') -Raw | ConvertFrom-Json
$representative=$run.suite -ceq 'representative'
$expectedCount=if($representative){39}else{7920}
if(-not$run.completed_requested_run -or $run.suite -notin @('all','representative') -or $run.mode -ne 'audio' -or
    $run.case_count -ne $expectedCount -or $run.repeat_count -ne 2 -or $run.results.Count -ne 2*$expectedCount){throw 'Incomplete full fresh-double baseline'}
if($representative -and $run.measurement_protocol -cne 'DeepPluck-CPU-Representative-20260903-Rev1'){throw 'Wrong representative protocol'}
$expected=if($representative){@{M=19;W=5;A=1;B=1;C=1;D=12}}else{@{M=2880;W=2880;X=1152;A=60;B=60;C=60;D=360;E=48;T1=36;T2=12;T3=12;T4=12;T5=24;T6=240;T7=60;T8=12;T9=12}}
$counts=@{};$byId=@{};$results=@{}
foreach($case in $run.cases){
    if($byId.ContainsKey($case.id)){throw 'Duplicate case ID'}
    $byId[$case.id]=$case
    if(-not$counts.ContainsKey($case.family)){$counts[$case.family]=0}
    $counts[$case.family]++
    if($case.raw_requested.Count -ne 62 -or $case.raw_applied.Count -ne 62 -or $case.normalized_applied.Count -ne 62){throw 'Incomplete parameter snapshot'}
}
foreach($family in $expected.Keys){if($counts[$family] -ne $expected[$family]){throw "Wrong family coverage: $family"}}
if($counts.Count -ne $expected.Count){throw 'Unexpected family'}
foreach($result in $run.results){
    $key="$($result.id)/$($result.repeat)"
    if(-not$byId.ContainsKey($result.id) -or $result.repeat -notin @(0,1) -or $results.ContainsKey($key)){throw 'Invalid/duplicate result'}
    $results[$key]=$result
}
$aliases=@{};$aliasMembers=0;$totalFrames=0L;$totalBytes=0L;$verifiedCases=0
foreach($id in $byId.Keys | Sort-Object){
    $case=$byId[$id];$a=$results["$id/0"];$b=$results["$id/1"]
    if(-not$a -or -not$b -or -not$b.equivalence.bit_identical -or $a.audio_sha256 -cne $b.audio_sha256 -or
       $a.lifecycle_sha256 -cne $b.lifecycle_sha256 -or $a.oscillator_and_lfo_phase_sha256 -cne $b.oscillator_and_lfo_phase_sha256 -or
       $a.manifest_sha256 -cne $b.manifest_sha256 -or $a.frames -ne $case.frames -or $b.frames -ne $case.frames){throw "Fresh render mismatch: $id"}
    $raw=Get-Item -LiteralPath (Join-Path $Root "$id-rep0.f32")
    if($raw.Length -ne 8L*$case.frames){throw "Truncated raw audio: $id"}
    if((Get-FileHash -LiteralPath $raw.FullName -Algorithm SHA256).Hash.ToLowerInvariant() -cne $a.audio_sha256){throw "Raw hash mismatch: $id"}
    $totalFrames+=[long]$case.frames;$totalBytes+=$raw.Length
    if($case.family -in @('M','W','X')){
        $input=[ordered]@{rate=$case.sample_rate;block=$case.nominal_block_size;frames=$case.frames;raw=$case.raw_applied;
            normalized=$case.normalized_applied;events=$case.events;parameterChanges=$case.parameter_changes_applied}
        $text=$input | ConvertTo-Json -Depth 20 -Compress
        $hash=[Security.Cryptography.SHA256]::Create()
        try{$inputHash=([BitConverter]::ToString($hash.ComputeHash([Text.Encoding]::UTF8.GetBytes($text)))).Replace('-','')}
        finally{$hash.Dispose()}
        if($aliases.ContainsKey($inputHash)){
            if($aliases[$inputHash].audioSha256 -cne $a.audio_sha256){throw "Identical-input aliases differ: $id"}
            $aliases[$inputHash].members.Add($id);$aliasMembers++
        }else{
            $members=[Collections.Generic.List[string]]::new();$members.Add($id)
            $aliases[$inputHash]=[ordered]@{inputSha256=$inputHash;audioSha256=$a.audio_sha256;members=$members}
        }
    }
    $verifiedCases++
    if($verifiedCases%1000 -eq 0){Write-Host "Verified $verifiedCases/7920 raw reference files ($($run.configuration))"}
}
$duplicates=@($aliases.Values | Where-Object {$_.members.Count -gt 1})
if(-not$representative -and $aliasMembers -lt 720){throw 'Expected M/W/X overlap coverage is missing'}
if($representative -and $aliasMembers -lt 1){throw 'Expected representative M/W shared-input check is missing'}
[ordered]@{configuration=$run.configuration;cases=$expectedCount;repeats=2;coverage=$counts;framesPerPass=$totalFrames;rawBytes=$totalBytes;
    allSamplesFreshBitIdentical=$true;allRawFilesRehashed=$true;uniqueMatrixInputs=$aliases.Count;duplicateInputMembers=$aliasMembers;
    duplicateGroups=$duplicates;manifestSha256=$run.selected_manifest_sha256;executableSha256=$run.executable_sha256;
    completedUtc=[DateTime]::UtcNow.ToString('o');fullMilestonePass=$false} | ConvertTo-Json -Depth 15 |
    Set-Content -LiteralPath $Report -Encoding utf8
Write-Host "PASS: $($run.configuration) fresh-double audio, $expectedCount cases, $aliasMembers identical-input aliases"
