# verify-binary.ps1
#
# Confirms a built ffmpeg.exe's own -buildconf output contains every flag in
# the checked-in config/ffmpeg.configure.args (PROJECT_PLAN.md: "the
# resulting ffmpeg -buildconf output ... must exactly match the checked-in
# configure arguments after normalised path differences"). The checked-in
# args file deliberately excludes path-bearing flags such as --prefix. The
# additive --extra-cflags/--extra-ldflags values are checked as substrings of
# FFmpeg's combined buildconf entries because configure merges repeated values
# (including the path-bearing AMF include flag added by build-ffmpeg.sh).
#
#   powershell -ExecutionPolicy Bypass -File scripts\verify-binary.ps1 -FfmpegPath <path>
#
# Exits non-zero if any checked-in flag is missing from -buildconf.

[CmdletBinding()]
param(
    [Parameter(Mandatory)][string]$FfmpegPath,
    [string]$WorkRoot = 'C:\nnffb'
)

$ErrorActionPreference = 'Stop'
Set-StrictMode -Version Latest
Import-Module (Join-Path $PSScriptRoot 'BuildCommon.psm1') -Force

$repoRoot = Get-RepoRoot
$argsFile = Join-Path $repoRoot 'config\ffmpeg.configure.args'
if (-not (Test-Path $FfmpegPath)) { throw "ffmpeg.exe not found: $FfmpegPath" }
if (-not (Test-Path $argsFile))   { throw "Checked-in configure args file not found: $argsFile" }

$paths = Get-BuildPaths $WorkRoot
New-Item -ItemType Directory -Force -Path $paths.manifests | Out-Null

Write-Host "=== Capturing -buildconf ===" -ForegroundColor Cyan
$psi = New-Object System.Diagnostics.ProcessStartInfo
$psi.FileName = $FfmpegPath; $psi.Arguments = '-hide_banner -buildconf'
$psi.UseShellExecute = $false; $psi.RedirectStandardOutput = $true; $psi.RedirectStandardError = $true
$psi.CreateNoWindow = $true
$p = [System.Diagnostics.Process]::Start($psi)
$stdout = $p.StandardOutput.ReadToEnd()
$p.WaitForExit(15000) | Out-Null
if ($p.ExitCode -ne 0) { throw "ffmpeg -buildconf exited $($p.ExitCode)" }

$buildconfPath = Join-Path $paths.manifests 'ffmpeg-buildconf.txt'
Set-Content -Path $buildconfPath -Value $stdout -Encoding UTF8

# Plain array + -notcontains rather than [HashSet[string]]::new(...): that
# generic constructor's overload resolution is unreliable in Windows
# PowerShell 5.1 ("Multiple ambiguous overloads found for 'new'"), proven
# against the target machine. The list here is a few dozen/hundred tokens,
# so the O(n*m) membership check is trivially fast.
$buildconfTokens = @(Get-BuildconfTokens -Text $stdout)

$expectedFlags = Get-Content $argsFile | ForEach-Object { $_.Trim() } | Where-Object { $_ -ne '' -and -not $_.StartsWith('#') }

function Test-ExpectedBuildconfFlag {
    param([Parameter(Mandatory)][string]$ExpectedFlag, [Parameter(Mandatory)][string[]]$BuildconfTokens)

    if ($ExpectedFlag -match '^(--extra-(?:cflags|ldflags))=(.+)$') {
        $prefix = $Matches[1]
        $requiredValue = $Matches[2]
        return @($BuildconfTokens | Where-Object {
            $_.StartsWith("$prefix=", [System.StringComparison]::Ordinal) -and
            $_.Substring($prefix.Length + 1).Trim('"', "'").Contains($requiredValue)
        }).Count -gt 0
    }

    $BuildconfTokens -contains $ExpectedFlag
}

Write-Host ("Checked-in flags: {0}" -f $expectedFlags.Count)
Write-Host ("Buildconf tokens: {0}" -f $buildconfTokens.Count)

$missing = @($expectedFlags | Where-Object { -not (Test-ExpectedBuildconfFlag -ExpectedFlag $_ -BuildconfTokens $buildconfTokens) })

$result = [ordered]@{
    schemaVersion  = 1
    checkedUtc     = (Get-Date).ToUniversalTime().ToString('o')
    ffmpegPath     = $FfmpegPath
    argsFile       = $argsFile
    argsFileSha256 = Get-FileSha256 $argsFile
    expectedCount  = $expectedFlags.Count
    buildconfFile  = $buildconfPath
    missingFlags   = $missing
    passed         = ($missing.Count -eq 0)
}
Write-JsonFile -Object $result -Path (Join-Path $paths.manifests 'verify-binary-result.json')

if ($missing.Count -gt 0) {
    Write-Host "`nMISSING from -buildconf (present in config/ffmpeg.configure.args but not in the built binary):" -ForegroundColor Red
    $missing | ForEach-Object { Write-Host "  $_" -ForegroundColor Red }
    Write-Host "`nFull -buildconf saved to $buildconfPath for inspection."
    throw "verify-binary FAILED: $($missing.Count) checked-in configure flag(s) missing from the built binary's -buildconf."
}

Write-Host "`nAll checked-in configure flags are present in the built binary's -buildconf." -ForegroundColor Green
Write-Host "Result: $(Join-Path $paths.manifests 'verify-binary-result.json')"
$result
