param(
  [Parameter(Mandatory = $true)] [string] $Worker,
  [Parameter(Mandatory = $true)] [string] $Source,
  [Parameter(Mandatory = $true)] [string] $Report,
  [Parameter(Mandatory = $true)] [string] $MediaBin,
  [Parameter(Mandatory = $true)] [string] $MingwBin
)

$ErrorActionPreference = 'Stop'
$appVerifier = Join-Path $env:SystemRoot 'System32\appverif.exe'
if (-not (Test-Path -LiteralPath $appVerifier)) { throw 'Application Verifier is not installed' }
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
$principal = [Security.Principal.WindowsPrincipal]::new($identity)
if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
  Write-Host 'Application Verifier requires an elevated Windows token; test skipped in this non-elevated release session'
  exit 125
}
$target = Split-Path -Leaf $Worker
$previousPath = $env:PATH
$env:PATH = "$(Split-Path -Parent $Worker);$MediaBin;$MingwBin;$env:SystemRoot\System32;$env:SystemRoot"
try {
  if (Test-Path -LiteralPath $Report) { Remove-Item -LiteralPath $Report -Force }
  Start-Process $appVerifier -ArgumentList @('-delete', 'logs', '-for', $target) -Wait -WindowStyle Hidden
  Start-Process $appVerifier -ArgumentList @('-enable', 'Heaps', 'Handles', '-for', $target) -Wait -WindowStyle Hidden
  & $Worker --probe --input $Source | Out-Null
  if ($LASTEXITCODE -ne 0) { throw "Application Verifier worker run failed with $LASTEXITCODE" }
  Start-Process $appVerifier -ArgumentList @('-export', 'log', '-for', $target, '-with', "To=$Report") -Wait -WindowStyle Hidden
  if (-not (Test-Path -LiteralPath $Report)) { throw 'Application Verifier did not export a report' }
  $xml = Get-Content -Raw -LiteralPath $Report
  if ($xml -match '<avrf:logEntry') { throw "Application Verifier reported a heap/handle defect: $Report" }
} finally {
  Start-Process $appVerifier -ArgumentList @('-delete', 'settings', '-for', $target) -Wait -WindowStyle Hidden
  $env:PATH = $previousPath
}
