# bootstrap_python.ps1 — make LatticeSearch's light installer self-sufficient WITHOUT bundling a
# runtime: detect Python 3.10+, install it if missing (winget, else the official silent installer),
# then install the LITE dependency (numpy) — offline from the bundled wheel when possible, online
# otherwise. Keeps the download small; the machine gets Python only if it doesn't already have it.
param(
    [string]$InstallDir = $PSScriptRoot,
    [string]$Wheels = (Join-Path (Split-Path $PSScriptRoot -Parent) 'wheels')
)
$ErrorActionPreference = 'Continue'

function Find-Python {
    foreach ($c in @(@('py', @('-3.10')), @('py', @('-3')), @('python', @()))) {
        $exe = $c[0]; $pre = $c[1]
        if (-not (Get-Command $exe -ErrorAction SilentlyContinue)) { continue }
        try {
            $v = & $exe @pre -c "import sys;print('%d.%d'%sys.version_info[:2])" 2>$null
            if ($LASTEXITCODE -eq 0 -and $v -match '^(\d+)\.(\d+)$') {
                if ([int]$Matches[1] -eq 3 -and [int]$Matches[2] -ge 10) { return , @($exe, $pre) }
            }
        } catch {}
    }
    return $null
}

$py = Find-Python
if (-not $py) {
    Write-Host 'Python 3.10+ not found - installing (this is a one-time step)...'
    $done = $false
    if (Get-Command winget -ErrorAction SilentlyContinue) {
        try {
            winget install -e --id Python.Python.3.10 --scope user --silent `
                --accept-package-agreements --accept-source-agreements | Out-Null
            $done = $true
        } catch { Write-Host "  winget path failed: $_" }
    }
    if (-not $done) {
        try {
            $url = 'https://www.python.org/ftp/python/3.10.11/python-3.10.11-amd64.exe'
            $tmp = Join-Path $env:TEMP 'python-3.10.11-amd64.exe'
            Write-Host "  downloading $url"
            Invoke-WebRequest -Uri $url -OutFile $tmp -UseBasicParsing
            Start-Process -FilePath $tmp -Wait `
                -ArgumentList '/quiet InstallAllUsers=0 PrependPath=1 Include_pip=1 Include_launcher=1'
        } catch { Write-Host "  installer download failed: $_" }
    }
    $env:Path = [Environment]::GetEnvironmentVariable('Path', 'User') + ';' +
                [Environment]::GetEnvironmentVariable('Path', 'Machine')
    $py = Find-Python
    if (-not $py) {
        Write-Host 'ERROR: Python 3.10 could not be installed automatically.'
        Write-Host 'Please install Python 3.10 from https://www.python.org/downloads/ and re-run the installer.'
        exit 1
    }
}

$exe = $py[0]; $pre = $py[1]
Write-Host "Using Python: $exe $($pre -join ' ')"
& $exe @pre -m pip install --disable-pip-version-check --no-warn-script-location -q --upgrade pip 2>$null

# LITE needs numpy (the name index + Hands). Try the bundled wheel first (offline), then PyPI.
$ok = $false
if (Test-Path $Wheels) {
    try {
        & $exe @pre -m pip install --no-index --find-links "$Wheels" numpy
        if ($LASTEXITCODE -eq 0) { $ok = $true }
    } catch {}
}
if (-not $ok) { & $exe @pre -m pip install numpy }
# pillow is optional (thumbnails) — best effort, never blocks the install
try { & $exe @pre -m pip install --no-index --find-links "$Wheels" pillow 2>$null } catch {}
if ($LASTEXITCODE -ne 0) { try { & $exe @pre -m pip install pillow 2>$null } catch {} }

Write-Host 'Python + LITE dependencies ready. (Semantic search is an optional upgrade: run setup_full.)'
exit 0
