[CmdletBinding()]
param(
  [string]$OutputMkv = "build\m2-roundtrip-gate.mkv",
  [string]$OutputReport = "build\m2-roundtrip-gate.json",
  [string]$SmartCutCli = ""
)

$projectRoot = Split-Path -Parent $PSScriptRoot
if ([string]::IsNullOrWhiteSpace($SmartCutCli)) { $SmartCutCli = Join-Path $projectRoot "build\ucrt64-ffmpeg\smartcut-cli.exe" }
if (-not (Test-Path -LiteralPath $SmartCutCli -PathType Leaf)) { throw "Missing FFmpeg-enabled SmartCut CLI: $SmartCutCli" }
$resolvedMkv = [System.IO.Path]::GetFullPath((Join-Path $projectRoot $OutputMkv))
$resolvedReport = [System.IO.Path]::GetFullPath((Join-Path $projectRoot $OutputReport))
New-Item -ItemType Directory -Path (Split-Path -Parent $resolvedMkv) -Force | Out-Null
New-Item -ItemType Directory -Path (Split-Path -Parent $resolvedReport) -Force | Out-Null
$savedPath = $env:Path
$env:Path = (Join-Path $projectRoot "artifacts\m1\bin") + ";C:\msys642\ucrt64\bin;" + $env:Path
try {
  & $SmartCutCli metadata-lab --generate-mkv $resolvedMkv
  if ($LASTEXITCODE -ne 0) { throw "MKV generation failed with exit code $LASTEXITCODE" }
  $inventoryJson = & $SmartCutCli metadata-lab --container --input $resolvedMkv --max-frames 5
  if ($LASTEXITCODE -ne 0) { throw "Container inventory failed with exit code $LASTEXITCODE" }
  $inventory = $inventoryJson | ConvertFrom-Json
  $gate = [ordered]@{
    schema = "metadata-lab-m2-gate-v1"
    output = $resolvedMkv
    decoded_frames = $inventory.decoded_frames
    decoded_is_10bit = $inventory.decoded_is_10bit
    packet_sei_nals = $inventory.packet_sei_nals
    packet_sei_variants = $inventory.packet_sei_variants
    hdr10plus_t35_bytes = $inventory.hdr10plus_t35_bytes
    hdr10plus_sei_bytes = $inventory.hdr10plus_sei_bytes
    passed = ($inventory.decoded_frames -ge 5 -and $inventory.decoded_is_10bit -and $inventory.packet_sei_nals -ge 5 -and $inventory.packet_sei_variants -gt 0 -and $inventory.hdr10plus_sei_bytes -gt 0)
    container_report = $inventory
  }
  $gate | ConvertTo-Json -Depth 8 | Set-Content -LiteralPath $resolvedReport -Encoding utf8
  Get-Content -LiteralPath $resolvedReport
  if (-not $gate.passed) { exit 5 }
}
finally { $env:Path = $savedPath }
