# package-win.ps1 — Build the Windows NSIS installer.
#
# better-sqlite3 is a native module and its binary must match the runtime ABI:
#   - packaged app / `npm start`  → Electron ABI (v130 for Electron 33)
#   - `npm run start:backend`     → Node ABI
# This script swaps the prebuilt binary to Electron ABI before packaging and
# restores the Node ABI afterwards, so dev backend mode keeps working.
#
# No compiler needed: prebuild-install downloads prebuilt binaries (uses the
# npm prebuild cache when GitHub is unreachable).
#
# Usage: powershell -ExecutionPolicy Bypass -File scripts/package-win.ps1

param([string]$ElectronVersion = "33.4.11")

$ErrorActionPreference = "Stop"
$root = Split-Path $PSScriptRoot
Set-Location $root

function Invoke-PrebuildInstall {
    param([string]$Runtime, [string]$Target)
    Push-Location "node_modules\better-sqlite3"
    try {
        if ($Runtime -eq "electron") {
            npx prebuild-install --runtime=electron --target=$Target
        } else {
            npx prebuild-install
        }
        if ($LASTEXITCODE -ne 0) { throw "prebuild-install ($Runtime) failed with exit code $LASTEXITCODE" }
    } finally {
        Pop-Location
    }
}

# 1) Swap better-sqlite3 to the Electron-ABI prebuilt binary.
Invoke-PrebuildInstall -Runtime electron -Target $ElectronVersion

try {
    # 2) Package. Point electron-builder at the local electron dist to skip the
    #    GitHub download, and mirror NSIS/winCodeSign through npmmirror (GitHub
    #    is unreachable on CN networks).
    $env:ELECTRON_BUILDER_BINARIES_MIRROR = "https://cdn.npmmirror.com/binaries/electron-builder-binaries/"
    $dist = Join-Path $root "node_modules\electron\dist"
    npx electron-builder --win "-c.electronDist=$dist"
    if ($LASTEXITCODE -ne 0) { throw "electron-builder failed with exit code $LASTEXITCODE" }
    Write-Host "[package] NSIS installer built:" -ForegroundColor Green
    Get-ChildItem "$root\dist\*.exe" | ForEach-Object { Write-Host "  $_" -ForegroundColor Green }
} finally {
    # 3) Restore the Node-ABI binary so `npm run start:backend` / `npm run dev` keep working.
    try {
        Invoke-PrebuildInstall -Runtime node
        Write-Host "[package] better-sqlite3 restored to Node ABI" -ForegroundColor Cyan
    } catch {
        Write-Host "[package] WARN: failed to restore Node prebuild: $($_.Exception.Message)" -ForegroundColor Yellow
    }
}
