param(
  [Parameter(Mandatory = $true)] [string] $Cli,
  [Parameter(Mandatory = $true)] [string] $Worker,
  [Parameter(Mandatory = $true)] [string] $WorkDir,
  [Parameter(Mandatory = $true)] [string] $MediaBin,
  [Parameter(Mandatory = $true)] [string] $MingwBin,
  [int64] $PeakLimitBytes = 1073741824
)

$ErrorActionPreference = 'Stop'
New-Item -ItemType Directory -Force -Path $WorkDir | Out-Null
  $fixture = Join-Path $WorkDir 'uhd-main10.mkv'
  $preview = Join-Path $WorkDir 'uhd-frame-7.ppm'
$stdout = Join-Path $WorkDir 'worker-output.json'
$stderr = Join-Path $WorkDir 'worker-error.txt'
$previousPath = $env:PATH
$env:PATH = "$(Split-Path -Parent $Worker);$MediaBin;$MingwBin;$env:SystemRoot\System32;$env:SystemRoot"
try {
  & $Cli make-performance-fixture --output $fixture --width 3840 --height 2160 --frames 8 | Out-Null
  if ($LASTEXITCODE -ne 0 -or -not (Test-Path -LiteralPath $fixture)) { throw 'UHD Main10 fixture generation failed' }
  $startInfo = [Diagnostics.ProcessStartInfo]::new()
  $startInfo.FileName = $Worker
  $startInfo.Arguments = "--preview-image --input `"$fixture`" --frame 7 --output `"$preview`""
  $startInfo.UseShellExecute = $false
  $startInfo.CreateNoWindow = $true
  $startInfo.RedirectStandardOutput = $true
  $startInfo.RedirectStandardError = $true
  $process = [Diagnostics.Process]::new()
  $process.StartInfo = $startInfo
  if (-not $process.Start()) { throw 'Could not start UHD worker' }
  [int64]$peak = 0
  while (-not $process.HasExited) {
    $process.Refresh()
    $peak = [Math]::Max($peak, $process.PeakWorkingSet64)
    Start-Sleep -Milliseconds 20
  }
  $workerOutput = $process.StandardOutput.ReadToEnd()
  $workerError = $process.StandardError.ReadToEnd()
  $process.WaitForExit()
  $process.Refresh()
  $peak = [Math]::Max($peak, $process.PeakWorkingSet64)
  [IO.File]::WriteAllText($stdout, $workerOutput)
  [IO.File]::WriteAllText($stderr, $workerError)
  if ($process.ExitCode -ne 0) { throw "UHD worker indexing failed with $($process.ExitCode): $workerError" }
  if (-not (Test-Path -LiteralPath $preview) -or (Get-Item -LiteralPath $preview).Length -lt 1000000) { throw 'UHD worker did not decode the requested final frame' }
  if ($peak -le 0 -or $peak -gt $PeakLimitBytes) { throw "UHD peak working set $peak exceeds limit $PeakLimitBytes" }
  [ordered]@{ schema='m13-uhd-memory-v1'; status='PASSED'; width=3840; height=2160; frames=8; peak_working_set_bytes=$peak; limit_bytes=$PeakLimitBytes; queue_policy='bounded-eight-frame-preview-cache' } | ConvertTo-Json -Compress | Set-Content -Encoding utf8 -LiteralPath (Join-Path $WorkDir 'm13-uhd-memory.json')
} finally { $env:PATH = $previousPath }
