$ErrorActionPreference = 'Stop'

<#
.SYNOPSIS
  Build a single-file, no-dependency Windows binary for BgVisionAgent.

.DESCRIPTION
  Uses PyInstaller to bundle the app and its Python dependencies into a single
  `BgVisionAgent.exe` suitable for systems without Python installed.

  Run this on Windows with Python 3.11 or 3.12 installed.

.EXAMPLE
  powershell -ExecutionPolicy Bypass -File scripts\build-win.ps1

.NOTES
  - Output: dist\BgVisionAgent.exe
  - You may need to run the resulting EXE as Administrator for global hotkeys.
  - To publish, copy the EXE to `bin/BgVisionAgent.exe` in this repo (or
    upload to your hosting and set BG_BINARY_URL accordingly in bootstrap).
#>

function Assert-Exe($exe) {
  $exists = Get-Command $exe -ErrorAction SilentlyContinue
  if (-not $exists) { throw "Required tool not found in PATH: $exe" }
}

Write-Host "[build] Preparing isolated venv..." -ForegroundColor Cyan
$root = Split-Path -Parent $MyInvocation.MyCommand.Path
Set-Location $root
Set-Location ..

$venv = Join-Path (Get-Location) ".build-venv"
if (Test-Path $venv) { Remove-Item $venv -Recurse -Force }

try {
  py -3 -m venv $venv
} catch {
  python -m venv $venv
}

$pip = Join-Path $venv "Scripts/pip.exe"
$python = Join-Path $venv "Scripts/python.exe"

& $pip install --upgrade pip wheel setuptools | Out-Null
& $pip install -r requirements.txt | Out-Null
& $pip install pyinstaller | Out-Null

Write-Host "[build] Running PyInstaller (one-file, windowed)..." -ForegroundColor Cyan

$common = @(
  "--noconfirm",
  "--clean",
  "-F",
  "-w",
  "-n","BgVisionAgent",
  "--collect-all","openai",
  "--collect-all","pyautogui",
  "--collect-all","pyscreeze",
  "--collect-all","mouseinfo",
  "--collect-all","pymsgbox",
  "--collect-all","pytweening",
  "--collect-all","pyperclip",
  "--collect-all","keyboard",
  "--collect-all","PIL",
  "--collect-all","certifi",
  "--hidden-import","win32api",
  "--hidden-import","win32gui",
  "--hidden-import","win32con"
)

& $python -m PyInstaller @common bg_agent/__main__.py

Write-Host "[build] Done. Binary at: dist\\BgVisionAgent.exe" -ForegroundColor Green
Write-Host "[build] Tip: copy dist\\BgVisionAgent.exe to bin\\BgVisionAgent.exe for bootstrap downloads." -ForegroundColor DarkGray

