# PicoBot build & package script
# Usage: .\scripts\build-release.ps1
# Output: dist\picobot-vX.X.X.zip

$ErrorActionPreference = "Stop"
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$Root = Split-Path -Parent $ScriptDir

# Read version
$CargoToml = Get-Content "$Root\Cargo.toml" -Raw
$Version = if ($CargoToml -match 'version\s*=\s*"([^"]+)"') { $Matches[1] } else { "0.1.0" }
$PackageName = "picobot-v$Version-windows-x86_64"
$DistDir = "$Root\dist\$PackageName"

Write-Host "=== PicoBot v$Version Build ===" -ForegroundColor Cyan

# Step 1: build frontend
Write-Host "[1/4] Building web frontend..." -ForegroundColor Yellow
Push-Location "$Root\web"
try {
    npm run build
    if ($LASTEXITCODE -ne 0) { throw "web build failed" }
} finally {
    Pop-Location
}

# Step 2: build Rust backend
Write-Host "[2/4] Building Rust release..." -ForegroundColor Yellow
Push-Location $Root
try {
    cargo build --release
    if ($LASTEXITCODE -ne 0) { throw "rust build failed" }
} finally {
    Pop-Location
}

# Step 3: assemble dist directory
Write-Host "[3/4] Assembling package..." -ForegroundColor Yellow
New-Item -ItemType Directory -Force -Path $DistDir | Out-Null

# exe + package contents
Copy-Item "$Root\target\release\picobot.exe" $DistDir
Copy-Item "$Root\package\*" $DistDir

# Step 4: zip
Write-Host "[4/4] Creating zip..." -ForegroundColor Yellow
$ZipPath = "$Root\dist\$PackageName.zip"
if (Test-Path $ZipPath) { Remove-Item $ZipPath }
Compress-Archive -Path $DistDir -DestinationPath $ZipPath

# Cleanup
Remove-Item -Recurse -Force $DistDir

Write-Host ""
Write-Host "=== Done ===" -ForegroundColor Green
Write-Host "Package: dist\$PackageName.zip" -ForegroundColor Green
Write-Host "Size: $([math]::Round((Get-Item $ZipPath).Length/1MB, 1)) MB" -ForegroundColor Gray
