$ErrorActionPreference = 'Stop'

# Simple, IEX-safe bootstrapper (no param / CmdletBinding)
# Usage (copy/paste):
#   iwr -useb https://git.meoww.cc/admin/openai-code-script-poc/raw/branch/master/bootstrap.ps1 | iex
# Optional: set OPENAI_API_KEY in the same command before piping.

function Test-PythonAvailable {
  try { & py -3 -V *> $null; return $true } catch {}
  try { & python -V *> $null; return $true } catch {}
  try { & python3 -V *> $null; return $true } catch {}
  return $false
}

function Start-Binary {
  param(
    [string]$DestDir,
    [string]$BinaryUrl
  )
  if (!(Test-Path $DestDir)) { New-Item -ItemType Directory -Path $DestDir | Out-Null }
  $exePath = Join-Path $DestDir 'BgVisionAgent.exe'
  Write-Host "Downloading binary from $BinaryUrl ..." -ForegroundColor DarkCyan
  iwr -useb $BinaryUrl -OutFile $exePath
  Write-Host "Launching BgVisionAgent.exe ..." -ForegroundColor Green
  Start-Process -FilePath $exePath -WindowStyle Hidden
  Write-Host "Agent started. Hotkeys:" -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 (if using source) or set OPENAI_API_KEY env var." -ForegroundColor Yellow
}

$ZipUrl   = 'https://git.meoww.cc/admin/openai-code-script-poc/archive/master.zip'
$BinaryUrl = $env:BG_BINARY_URL
if (-not $BinaryUrl) { $BinaryUrl = 'https://git.meoww.cc/admin/openai-code-script-poc/raw/branch/master/bin/BgVisionAgent.exe' }

$Dest   = Join-Path $env:USERPROFILE 'BgVisionAgent'
$Force  = ($env:BG_FORCE -eq '1' -or $env:BG_FORCE -eq 'true')
$UseBin = ($env:BG_USE_BINARY -eq '1' -or $env:BG_USE_BINARY -eq 'true')

Write-Host "Bootstrap: preparing -> $Dest" -ForegroundColor Cyan
if (Test-Path $Dest) {
  if ($Force) {
    Write-Host "Removing existing destination (BG_FORCE=1)..." -ForegroundColor DarkYellow
    Remove-Item $Dest -Recurse -Force
  }
}

# Prefer prebuilt binary when requested or when Python isn't available
if ($UseBin -or -not (Test-PythonAvailable)) {
  try {
    Start-Binary -DestDir $Dest -BinaryUrl $BinaryUrl
    return
  } catch {
    Write-Host "Binary path failed; falling back to source ZIP path..." -ForegroundColor DarkYellow
  }
}

if (!(Test-Path $Dest)) { New-Item -ItemType Directory -Path $Dest | Out-Null }

$root = $Dest
$zip = Join-Path $env:TEMP 'bgagent.zip'

Write-Host "Downloading ZIP from $ZipUrl ..." -ForegroundColor DarkCyan
iwr -useb $ZipUrl -OutFile $zip

Write-Host "Expanding archive to $Dest ..." -ForegroundColor DarkCyan
Expand-Archive $zip -DestinationPath $Dest -Force

# If the ZIP contains a single top-level folder, use it as root
$sub = Get-ChildItem $Dest | Where-Object { $_.PSIsContainer } | Select-Object -First 1
if ($sub) { $root = $sub.FullName }

Set-Location $root
Write-Host "Invoking run.ps1 ..." -ForegroundColor Green
try {
  & .\run.ps1
} catch {
  Write-Host "run.ps1 failed to execute in-session. Retrying via Bypass..." -ForegroundColor DarkYellow
  powershell -NoProfile -ExecutionPolicy Bypass -File .\run.ps1
}

Write-Host "Bootstrap completed." -ForegroundColor Green
