param(
  [switch]$Cuda
)

$ErrorActionPreference = "Stop"
$pluginRoot = Split-Path -Parent $PSScriptRoot
$sourceRoot = Join-Path $pluginRoot "backend\transcription\worker-native"
$backend = if ($Cuda) { "cuda" } else { "cpu" }
$buildRoot = Join-Path $env:TEMP "lumi-whisper-worker-$backend"
$targetRoot = Join-Path $pluginRoot "data\runtime\worker\windows-x64-$backend\bin"

function Find-Tool([string]$name) {
  $command = Get-Command $name -ErrorAction SilentlyContinue
  if ($command) { return $command.Source }
  $candidate = Get-ChildItem (Join-Path $env:APPDATA "Python\Python*\Scripts\$name") -ErrorAction SilentlyContinue |
    Sort-Object FullName -Descending |
    Select-Object -First 1
  if ($candidate) { return $candidate.FullName }
  throw "$name was not found. Install CMake and Ninja before building the transcription worker."
}

$cmake = Find-Tool "cmake.exe"
$ninja = Find-Tool "ninja.exe"
$vcvars = Get-ChildItem "${env:ProgramFiles(x86)}\Microsoft Visual Studio\2022\*\VC\Auxiliary\Build\vcvars64.bat" -ErrorAction SilentlyContinue |
  Select-Object -First 1
if (!$vcvars) { throw "Visual Studio 2022 C++ Build Tools were not found." }

New-Item -ItemType Directory -Force -Path $buildRoot, $targetRoot | Out-Null
$cudaValue = if ($Cuda) { "ON" } else { "OFF" }
$buildScript = Join-Path $buildRoot "build-worker.cmd"
@(
  "@echo off",
  ('call "{0}" >nul' -f $vcvars.FullName),
  ('"{0}" -S "{1}" -B "{2}" -G Ninja -DLUMI_WHISPER_CUDA={3} -DCMAKE_BUILD_TYPE=Release -DCMAKE_MAKE_PROGRAM="{4}"' -f $cmake, $sourceRoot, $buildRoot, $cudaValue, $ninja),
  "if errorlevel 1 exit /b %errorlevel%",
  ('"{0}" --build "{1}" --config Release' -f $cmake, $buildRoot),
  "exit /b %errorlevel%"
) | Set-Content -Encoding Ascii $buildScript
$commandProcessor = Join-Path $env:SystemRoot "System32\cmd.exe"
$process = Start-Process -FilePath $commandProcessor -ArgumentList "/d /c $buildScript" -Wait -PassThru -NoNewWindow
if ($process.ExitCode -ne 0) { throw "Worker build failed with exit code $($process.ExitCode)." }

$worker = Join-Path $buildRoot "lumi-whisper-worker.exe"
if (!(Test-Path $worker)) { throw "The build completed without producing lumi-whisper-worker.exe." }
Copy-Item -Force $worker (Join-Path $targetRoot "lumi-whisper-worker.exe")
Write-Host "Installed Lumi whisper worker ($backend) in $targetRoot"
