param(
    [Parameter(Mandatory=$true)][string]$FullPairedAnalysis,
    [Parameter(Mandatory=$true)][string]$CandidatePhaseAnalysis,
    [Parameter(Mandatory=$true)][string]$CandidateExecutable,
    [Parameter(Mandatory=$true)][string]$Experiment,
    [Parameter(Mandatory=$true)][string]$FirstConfirmation,
    [Parameter(Mandatory=$true)][string]$SecondConfirmation,
    [Parameter(Mandatory=$true)][string]$LatencyReview,
    [string[]]$RegressionConfirmations=@(),
    [Parameter(Mandatory=$true)][string]$Report
)
$ErrorActionPreference='Stop'
. (Join-Path $PSScriptRoot 'CPUReportIO.ps1')
if(-not[IO.Path]::IsPathRooted($Report) -or (Test-Path -LiteralPath $Report)){throw 'Use a new absolute gate report path'}
function Read([string]$Path){Get-Content -LiteralPath $Path -Raw | ConvertFrom-Json}
function Assert([bool]$Condition,[string]$Message){if(-not$Condition){throw $Message}}
function Hash([string]$Path){(Get-FileHash -LiteralPath $Path -Algorithm SHA256).Hash}
$record=[ordered]@{schema='DeepPluck-CPU-Performance-Acceptance-Rev1';startedUtc=[DateTime]::UtcNow.ToString('o');
    performancePass=$false;fullMilestonePass=$false;error=$null}
try{
    $full=Read $FullPairedAnalysis;$phases=Read $CandidatePhaseAnalysis;$experimentData=Read $Experiment
    $first=Read $FirstConfirmation;$second=Read $SecondConfirmation;$review=Read $LatencyReview
    $candidateHash=Hash $CandidateExecutable
    Assert (-not$full.syntheticUnitFixture -and $full.caseCount -eq 39 -and $full.pairCount -eq 5 -and
        $full.candidateVersion -ceq '0.11.5' -and $full.candidateExecutableSha256 -ieq $candidateHash -and
        $full.alternatingSequentialOrderVerified -and $full.allOriginalPairsRetained -and $full.candidateHardGatesPass) 'Full genuine five-pair candidate hard gates are incomplete'
    $ids=@(& $CandidateExecutable --suite representative --list | Where-Object {$_ -notlike '#*'})
    Assert ($LASTEXITCODE -eq 0 -and $ids.Count -eq 39 -and @($full.caseIds | Sort-Object -Unique).Count -eq 39) 'Invalid complete representative inventory'
    $set=@{};foreach($id in $full.caseIds){$set[$id]=$true}
    foreach($id in $ids){Assert ($set.ContainsKey($id)) "Missing performance case: $id"}
    Assert ($phases.caseCount -eq 39 -and $phases.repeatCount -eq 5 -and
        $phases.executableSha256 -ieq $candidateHash -and $phases.sourceSha256 -ceq $full.candidateSourceSha256 -and
        $phases.environmentSha256 -ceq $full.candidateEnvironmentSha256 -and
        $phases.comparisonEnvironmentSha256 -ceq $full.comparisonEnvironmentSha256 -and
        $null -ne $phases.dynamicPhaseViolations -and $phases.dynamicPhaseViolations.Count -eq 0) 'Dynamic lifecycle phase hard gates are incomplete'
    Assert ($experimentData.schema -ceq 'DeepPluck-CPU-Experiment-Rev1' -and $experimentData.productionChange -and
        -not$experimentData.fpReorderingException -and $experimentData.hypothesis -and $experimentData.sourceLocations.Count -gt 0 -and
        $experimentData.hotspotCaseId -in $ids -and $experimentData.typicalCaseId -like 'B-*' -and
        $experimentData.worstBaselineDCaseId -like 'D-*') 'Missing preregistered production optimisation'
    Assert ((Hash $experimentData.baselineSelection.path) -ieq $experimentData.baselineSelection.sha256) 'Missing unchanged slowest-D selection evidence'
    $selection=Read $experimentData.baselineSelection.path
    Assert ($selection.caseCount -eq 39 -and $selection.repeatCount -eq 5 -and
        $selection.executableSha256 -ieq $full.baselineExecutableSha256 -and
        $selection.sourceSha256 -ceq $full.baselineSourceSha256 -and
        $selection.environmentSha256 -ceq $full.environmentSha256 -and
        $selection.worstD.id -ceq $experimentData.worstBaselineDCaseId) 'D selection does not match the full measured baseline'
    $requiredCases=@(@($experimentData.hotspotCaseId,$experimentData.typicalCaseId,$experimentData.denseCaseId,$experimentData.worstBaselineDCaseId) | Sort-Object -Unique)
    $profiledIds=@{}
    Assert ($experimentData.profiles.Count -eq 3) 'Exactly Typical, Dense and measured Worst profiling workloads required'
    foreach($profile in $experimentData.profiles){
        Assert ($profile.symbolsResolved -and $profile.durationSeconds -ge 30 -and $profile.callbackSamples -gt 0 -and
            $profile.profiler -and $profile.caseId -in $ids -and $profile.sourceLocations.Count -gt 0) 'Insufficient actual profiling evidence'
        foreach($item in @($profile.trace,$profile.callTree,$profile.hotPath)){
            Assert ($item.path -and $item.sha256 -cmatch '^[a-fA-F0-9]{64}$' -and
                (Hash $item.path) -ieq $item.sha256) 'Missing or changed profiling trace/call-tree/hot-path evidence'
        }
        $profiledIds[$profile.caseId]=$true
    }
    foreach($id in $requiredCases){Assert ($profiledIds.ContainsKey($id)) "Required measured case has no genuine profile: $id"}
    Assert (@($experimentData.profiles | Where-Object {$_.caseId -like 'C-*'}).Count -eq 1) 'Missing Dense profile'
    Assert (@($experimentData.profiles | Where-Object {$_.caseId -notmatch '^[BCD]-'}).Count -eq 0) 'Profile outside approved Typical/Dense/Worst scope'
    Assert ([IO.Path]::GetFullPath($FirstConfirmation) -ne [IO.Path]::GetFullPath($SecondConfirmation) -and
        $first.pairedRoot -ne $second.pairedRoot) 'Confirmation must be a second independent original run'
    foreach($confirmationFile in @($FirstConfirmation,$SecondConfirmation)){
        $confirmation=Read $confirmationFile
        Assert (-not$confirmation.syntheticUnitFixture -and $confirmation.pairCount -eq 9 -and
            $confirmation.caseCount -eq $requiredCases.Count -and $confirmation.alternatingSequentialOrderVerified -and
            $confirmation.allOriginalPairsRetained -and $confirmation.candidateHardGatesPass -and
            $confirmation.candidateVersion -ceq $full.candidateVersion -and
            $confirmation.baselineVersion -ceq $full.baselineVersion -and
            $confirmation.candidateExecutableSha256 -ieq $candidateHash -and
            $confirmation.baselineExecutableSha256 -ieq $full.baselineExecutableSha256 -and
            $confirmation.candidateSourceSha256 -ceq $full.candidateSourceSha256 -and
            $confirmation.baselineSourceSha256 -ceq $full.baselineSourceSha256 -and
            $confirmation.environmentSha256 -ceq $full.environmentSha256 -and
            $confirmation.candidateEnvironmentSha256 -ceq $full.candidateEnvironmentSha256 -and
            $confirmation.comparisonEnvironmentSha256 -ceq $full.comparisonEnvironmentSha256) 'Invalid independent nine-pair confirmation'
        foreach($id in $requiredCases){Assert ($id -in $confirmation.caseIds) "Missing confirmation case: $id"}
        $rows=@($confirmation.comparisons | Where-Object {$_.id -ceq $experimentData.hotspotCaseId -and $_.phase -ceq 'total'})
        Assert ($rows.Count -eq 1) 'Missing hotspot whole-case comparison'
        $stats=$rows[0].statistics
        Assert ($stats.seed -ceq '0xD0115001' -and $stats.engine -ceq 'std::mt19937' -and $stats.resamples -eq 10000 -and
            $stats.lower_index -eq 249 -and $stats.upper_index -eq 9750 -and $stats.rejection_limit -eq 4294967292 -and
            $stats.improvement.median_percent -ge 5 -and $stats.improvement.ci95_lower_percent -gt 0 -and
            $stats.efficiency_threshold_pass) 'Profiled hotspot gain is not twice independently confirmed'
        Assert (@($confirmation.comparisons | Where-Object {$_.statistics.confirmed_regression}).Count -eq 0) 'Confirmed regression in optimisation case set'
        $execution=Import-Csv -LiteralPath (Join-Path (Split-Path -Parent $confirmationFile) 'execution-order.csv')
        Assert (@($execution).Count -eq 18*$requiredCases.Count) 'Missing confirmation timestamps'
        foreach($row in $execution){Assert ([DateTimeOffset]$row.startUtc -gt [DateTimeOffset]$experimentData.registeredUtc) 'Optimisation was not preregistered before measurement'}
    }
    $probes=@{};foreach($path in $RegressionConfirmations){
        $probe=Read $path
        Assert (-not$probe.syntheticUnitFixture -and $probe.pairCount -eq 9 -and $probe.alternatingSequentialOrderVerified -and
            $probe.allOriginalPairsRetained -and $probe.candidateHardGatesPass -and
            $probe.candidateVersion -ceq $full.candidateVersion -and $probe.baselineVersion -ceq $full.baselineVersion -and
            $probe.candidateExecutableSha256 -ieq $candidateHash -and
            $probe.baselineExecutableSha256 -ieq $full.baselineExecutableSha256 -and
            $probe.candidateSourceSha256 -ceq $full.candidateSourceSha256 -and
            $probe.baselineSourceSha256 -ceq $full.baselineSourceSha256 -and
            $probe.environmentSha256 -ceq $full.environmentSha256 -and
            $probe.candidateEnvironmentSha256 -ceq $full.candidateEnvironmentSha256 -and
            $probe.comparisonEnvironmentSha256 -ceq $full.comparisonEnvironmentSha256) 'Invalid regression probe'
        foreach($row in $probe.comparisons){$probes["$($row.id)/$($row.phase)"]=$row}
    }
    foreach($suspect in @($full.comparisons | Where-Object {$_.suspectedRegression})){
        $key="$($suspect.id)/$($suspect.phase)"
        Assert ($probes.ContainsKey($key)) "Missing nine-pair regression confirmation: $key"
        Assert (-not$probes[$key].statistics.confirmed_regression) "Confirmed performance regression: $key"
    }
    Assert ($review.schema -ceq 'DeepPluck-CPU-Latency-Review-Rev1' -and
        $review.fullPairedAnalysisSha256 -ieq (Hash $FullPairedAnalysis) -and $review.conclusion -and
        $review.timerOverheadReviewed -and $review.allP99AndMaxChangesReviewed -and -not$review.inconclusive) 'Timer/P99/max stability review missing or inconclusive'
    $record.performancePass=$true
    $record.candidateVersion='0.11.5';$record.candidateExecutableSha256=$candidateHash
    $record.cases=39;$record.protocol='DeepPluck-CPU-Representative-20260903-Rev1';$record.finalPairs=5;$record.independentConfirmations=2;$record.pairsPerConfirmation=9
    $record.profiledHotspot=$experimentData.hotspotCaseId
    $record.evidence=@($FullPairedAnalysis,$CandidatePhaseAnalysis,$Experiment,$FirstConfirmation,$SecondConfirmation,$LatencyReview)+$RegressionConfirmations
    Write-Host 'PASS: controlled performance acceptance. Audio, compatibility, artifacts, build/tests and manual acceptance remain separate.'
}catch{$record.error=$_.Exception.Message;throw}
finally{
    $record.completedUtc=[DateTime]::UtcNow.ToString('o')
    $record | ConvertTo-Json -Depth 20 | Set-Content -LiteralPath $Report -Encoding utf8
}
