# build-release.ps1
# Builds a portable SINGLE-FILE release for Windows and Mac

Write-Host "Starting Portable Release Build..." -ForegroundColor Cyan

# 1. Clean previous build
if (Test-Path "Release") { Remove-Item "Release" -Recurse -Force }
if (Test-Path "backend\dist") { Remove-Item "backend\dist" -Recurse -Force }
New-Item -ItemType Directory -Force -Path "Release" | Out-Null
New-Item -ItemType Directory -Force -Path "Release\Windows" | Out-Null
New-Item -ItemType Directory -Force -Path "Release\Mac" | Out-Null

# 2. Build Frontend
Write-Host "Building Frontend (Vite)..." -ForegroundColor Yellow
$pkgManager = "pnpm"
if (-not (Get-Command "pnpm" -ErrorAction SilentlyContinue)) { $pkgManager = "npm" }

Invoke-Expression "$pkgManager install"
Invoke-Expression "$pkgManager run build"

if (-not (Test-Path "dist")) {
    Write-Host "Frontend build failed: 'dist' folder not found." -ForegroundColor Red
    exit 1
}

# 3. Move dist to backend/dist (for embedding)
Write-Host "Moving frontend to backend for embedding..." -ForegroundColor Cyan
Copy-Item -Path "dist" -Destination "backend\dist" -Recurse

# 4. Build Backend
Write-Host "Building Backend..." -ForegroundColor Yellow

# Windows Build
Write-Host "  Windows (amd64)..." -ForegroundColor Cyan
$env:GOOS = "windows"; $env:GOARCH = "amd64"
go build -ldflags "-s -w -H=windowsgui" -o "Release\Windows\Antigravity.exe" backend/main.go

# Mac Build (Cross-compile)
Write-Host "  macOS (amd64 & arm64)..." -ForegroundColor Cyan
$env:GOOS = "darwin"; $env:GOARCH = "amd64"
go build -ldflags "-s -w" -o "Release\Mac\Antigravity-Intel" backend/main.go

$env:GOARCH = "arm64"
go build -ldflags "-s -w" -o "Release\Mac\Antigravity-AppleSilicon" backend/main.go

# Cleanup backend/dist
Remove-Item "backend\dist" -Recurse -Force

# 5. Success Message & Zipping
Write-Host "Build Complete!" -ForegroundColor Green

# Zip Windows
if (Test-Path "Release\Antigravity-Windows.zip") { Remove-Item "Release\Antigravity-Windows.zip" }
Compress-Archive -Path "Release\Windows\*" -DestinationPath "Release\Antigravity-Windows.zip" -Force
Write-Host "Created Windows Zip: Release\Antigravity-Windows.zip" -ForegroundColor Green

# Zip Mac
if (Test-Path "Release\Antigravity-Mac.zip") { Remove-Item "Release\Antigravity-Mac.zip" }
Compress-Archive -Path "Release\Mac\*" -DestinationPath "Release\Antigravity-Mac.zip" -Force
Write-Host "Created Mac Zip: Release\Antigravity-Mac.zip" -ForegroundColor Green

Write-Host "Artifacts are in the 'Release' folder." -ForegroundColor White
