# diagnose-libvpl.ps1
#
# One-off diagnostic for the "libvpl >= 2.6 not found" configure failure.
# Not part of the regular pipeline -- run manually, paste the output back.
#
# Round 2: pkg-config resolves vpl fine standalone (exists_rc=0,
# modversion_rc=0), so this pass looks at what FFmpeg's own configure saw --
# it checks pkg-config AND that mfxvideo.h/mfxdispatcher.h compile AND that
# MFXLoad links, not just that pkg-config resolves the module.
#
#   powershell -ExecutionPolicy Bypass -File scripts\diagnose-libvpl.ps1

[CmdletBinding()]
param([string]$WorkRoot = 'C:\nnffb')

$ErrorActionPreference = 'Continue'
$ffmpegDir = Join-Path $WorkRoot 'sources\ffmpeg-8.1.2'
# FFmpeg 8.1.2's configure writes its own log to ffbuild/config.log (relative
# to the source dir), not config.log at the source root -- confirmed via
# configure:4336 "logfile=ffbuild/config.log".
$configLog = Join-Path $ffmpegDir 'ffbuild\config.log'
$configureLog = Join-Path $ffmpegDir 'ffbuild-configure.log'

Write-Host "=== ffbuild-configure.log: context around the libvpl failure ===" -ForegroundColor Cyan
if (Test-Path $configureLog) {
    $lines = Get-Content $configureLog
    $idx = ($lines | Select-String -Pattern 'libvpl|vpl >= 2\.6' | Select-Object -Last 1).LineNumber
    if ($idx) {
        $start = [Math]::Max(0, $idx - 30)
        $lines[$start..([Math]::Min($lines.Count - 1, $idx + 5))]
    } else {
        Write-Host "No 'libvpl' mention found -- showing last 40 lines instead:"
        $lines | Select-Object -Last 40
    }
} else {
    Write-Host "NOT FOUND: $configureLog" -ForegroundColor Red
}

Write-Host "`n=== config.log: every pkg-config / vpl / mfx invocation ===" -ForegroundColor Cyan
if (Test-Path $configLog) {
    Write-Host ("(full log: {0}, {1} lines)" -f $configLog, (Get-Content $configLog | Measure-Object -Line).Lines)
    Select-String -Path $configLog -Pattern 'pkg-config|pkgconf|mfxvideo|mfxdispatcher|MFXLoad|check_pkg_config|libmfx|BEGIN \d|END \d' -Context 1,4 |
        ForEach-Object { $_.Context.PreContext; ">> $($_.Line)"; $_.Context.PostContext; "---" }
} else {
    Write-Host "NOT FOUND: $configLog" -ForegroundColor Red
}

Write-Host "`n=== PATH inside the exact same MSYS2 invocation build-ffmpeg.sh uses ===" -ForegroundColor Cyan
$msysBash = Join-Path $WorkRoot 'msys64\usr\bin\bash.exe'
$env:MSYSTEM = 'UCRT64'
& $msysBash -lc "which pkg-config; pkg-config --version; which gcc; echo PATH=`$PATH"
