[CmdletBinding()]
param(
  [Parameter(Mandatory = $true)][string]$InputHevc,
  [Parameter(Mandatory = $true)][string]$RpuFile,
  [Parameter(Mandatory = $true)][string]$OutputReport,
  [string]$DoviTool = "",
  [string]$SmartCutCli = ""
)

$projectRoot = Split-Path -Parent $PSScriptRoot
if ([string]::IsNullOrWhiteSpace($DoviTool)) { $DoviTool = Join-Path $projectRoot "artifacts\m1\bin\dovi_tool.exe" }
if ([string]::IsNullOrWhiteSpace($SmartCutCli)) { $SmartCutCli = Join-Path $projectRoot "build\ucrt64-ffmpeg\smartcut-cli.exe" }
foreach ($path in @($DoviTool, $SmartCutCli, $InputHevc, $RpuFile)) {
  if (-not (Test-Path -LiteralPath $path -PathType Leaf)) { throw "Missing file: $path" }
}
$tempJson = Join-Path ([System.IO.Path]::GetTempPath()) ("smartcut-rpu-" + [guid]::NewGuid().ToString("N") + ".json")
$savedPath = $env:Path
$ucrtBin = "C:\msys642\ucrt64\bin"
$env:Path = (Join-Path $projectRoot "artifacts\m1\bin") + ";" + $ucrtBin + ";" + $env:Path
try {
  & $DoviTool export --input $RpuFile --data ("all=" + $tempJson) | Out-Host
  if ($LASTEXITCODE -ne 0) { throw "dovi_tool export failed with exit code $LASTEXITCODE" }
  $rpuRecords = Get-Content -LiteralPath $tempJson -Raw | ConvertFrom-Json
  $inventoryJson = & $SmartCutCli metadata-lab --input $InputHevc --codec hevc
  if ($LASTEXITCODE -ne 0) { throw "SmartCut64 NAL inventory failed with exit code $LASTEXITCODE" }
  $inventory = $inventoryJson | ConvertFrom-Json
  $report = [ordered]@{
    schema = "metadata-lab-rpu-roundtrip-v1"
    input = [System.IO.Path]::GetFullPath($InputHevc)
    rpu_source = [System.IO.Path]::GetFullPath($RpuFile)
    rpu_records = $rpuRecords.Count
    hevc_rpu_nals = $inventory.summary.dolby_vision_rpu_units
    coverage_complete = ($rpuRecords.Count -eq $inventory.summary.dolby_vision_rpu_units)
    source_report_schema = $inventory.schema
  }
  $resolvedOutput = [System.IO.Path]::GetFullPath($OutputReport)
  $outputDirectory = Split-Path -Parent $resolvedOutput
  if (-not (Test-Path -LiteralPath $outputDirectory -PathType Container)) { New-Item -ItemType Directory -Path $outputDirectory -Force | Out-Null }
  $report | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath $resolvedOutput -Encoding utf8
  Get-Content -LiteralPath $resolvedOutput
  if (-not $report.coverage_complete) { exit 4 }
}
finally {
  $env:Path = $savedPath
  Remove-Item -LiteralPath $tempJson -Force -ErrorAction SilentlyContinue
}
