$ErrorActionPreference = "Stop"

Write-Host "Setting up and launching Background Vision Agent..." -ForegroundColor Cyan

$root = Split-Path -Parent $MyInvocation.MyCommand.Path
Set-Location $root

$venv = Join-Path $root ".venv"
if (!(Test-Path $venv)) {
  Write-Host "Creating venv..." -ForegroundColor DarkCyan
  try {
    py -3 -m venv $venv
  } catch {
    python -m venv $venv
  }
}

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

# Graceful handling when Python is not present / venv creation failed
if (!(Test-Path $python)) {
  Write-Host "Python/venv not available. You can either:" -ForegroundColor Yellow
  Write-Host "  1) Install Python 3.11+ (winget install -e --id Python.Python.3.11), or" -ForegroundColor Yellow
  Write-Host "  2) Use the prebuilt binary: set BG_USE_BINARY=1 and run bootstrap.ps1" -ForegroundColor Yellow
  Write-Host "     iwr -useb https://git.meoww.cc/admin/openai-code-script-poc/raw/branch/master/bootstrap.ps1 | iex" -ForegroundColor DarkGray
  throw "Python interpreter not found at $python"
}

& $python -m pip install --upgrade pip | Out-Null
& $python -m pip install -r (Join-Path $root "requirements.txt")

Write-Host "Starting agent in background (hidden)..." -ForegroundColor DarkCyan
Start-Process -FilePath $pythonw -ArgumentList "-m","bg_agent" -WindowStyle Hidden

Write-Host "Agent started. Use the hotkeys below:" -ForegroundColor Green
Write-Host "  Ctrl+Shift+1  -> Capture active window"
Write-Host "  Ctrl+Shift+2  -> Send to OpenAI"
Write-Host "  Ctrl+Shift+3  -> Action 3 (type or clipboard mode)"
Write-Host "  Ctrl+Shift+4  -> Reset state"
Write-Host "  Ctrl+Shift+5  -> Quit (press 3 times quickly)"
Write-Host "  Ctrl+Shift+6  -> Switch modes for Action 3"

Write-Host "Configure API key in bg_agent/config.py or set OPENAI_API_KEY env var." -ForegroundColor Yellow
