$ErrorActionPreference = 'Stop'

[CmdletBinding()]
param(
  [string] $ApiKey,
  [string] $BaseUrl,
  [string] $Dest = (Join-Path $env:USERPROFILE 'BgVisionAgent'),
  [switch] $Force
)

# ---- Source configuration (edit these before hosting, or pass params) ----
$RepoUrl = ''     # e.g. https://github.com/you/openai-code-script-poc.git
$ZipUrl  = 'https://git.meoww.cc/admin/openai-code-script-poc/archive/master.zip'     # e.g. https://your.domain/downloads/bgvisionagent.zip
$Branch  = 'main' # used only for git
# -------------------------------------------------------------------------

function Have($name) { Get-Command $name -ErrorAction SilentlyContinue }

Write-Host "Bootstrap: preparing destination -> $Dest" -ForegroundColor Cyan
if (Test-Path $Dest) {
  if ($Force) {
    Write-Host "Removing existing destination (Force)..." -ForegroundColor DarkYellow
    Remove-Item $Dest -Recurse -Force
  }
}
if (!(Test-Path $Dest)) { New-Item -ItemType Directory -Path $Dest | Out-Null }

$root = $Dest

if ($ZipUrl) {
  $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 }
}
elseif ($RepoUrl -and (Have 'git')) {
  if (Test-Path (Join-Path $Dest '.git')) {
    Write-Host "Updating existing git repo..." -ForegroundColor DarkCyan
    Push-Location $Dest
    git fetch --all --prune
    git checkout $Branch 2>$null
    git pull --ff-only
    Pop-Location
  } else {
    Write-Host "Cloning $RepoUrl -> $Dest ..." -ForegroundColor DarkCyan
    git clone --branch $Branch --depth 1 $RepoUrl $Dest
  }
}
else {
  Write-Host "No ZIP URL and git not available or RepoUrl empty. Nothing to fetch." -ForegroundColor Red
  Write-Host "Edit bootstrap.ps1 to set $RepoUrl or $ZipUrl, or pass -Dest with files present." -ForegroundColor Yellow
}

# Optionally set env vars for this session (inherited by run.ps1 and pythonw)
if ($ApiKey)  { $env:OPENAI_API_KEY = $ApiKey }
if ($BaseUrl) { $env:OPENAI_BASE_URL = $BaseUrl }

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
