param(
  [Parameter(Mandatory = $true)][string]$Worker,
  [Parameter(Mandatory = $true)][string]$Cli
)

$ErrorActionPreference = 'Stop'
$pipeName = 'smartcut-ctest-' + [guid]::NewGuid().ToString('N')
$server = $null
try {
  $server = Start-Process -FilePath $Worker -ArgumentList '--control-server', '--pipe', $pipeName -WindowStyle Hidden -PassThru
  $pingText = & $Cli ipc-ping --pipe $pipeName
  if ($LASTEXITCODE -ne 0) { throw 'IPC ping command failed' }
  $ping = $pingText | ConvertFrom-Json
  if ($ping.schema -ne 'control-response-v1' -or -not $ping.ok -or $ping.protocol_version -ne 1 -or $ping.pid -le 0) {
    throw "Invalid IPC ping response: $pingText"
  }
  $shutdownText = & $Cli ipc-shutdown --pipe $pipeName
  if ($LASTEXITCODE -ne 0) { throw 'IPC shutdown command failed' }
  $shutdown = $shutdownText | ConvertFrom-Json
  if ($shutdown.schema -ne 'control-response-v1' -or -not $shutdown.ok -or -not $shutdown.shutdown) {
    throw "Invalid IPC shutdown response: $shutdownText"
  }
  if (-not $server.WaitForExit(5000) -or $server.ExitCode -ne 0) { throw 'IPC worker did not shut down cleanly' }
  Write-Host 'Versioned length-prefixed named-pipe control IPC passed'
}
finally {
  if ($null -ne $server -and -not $server.HasExited) { Stop-Process -Id $server.Id -Force }
}
