<#
.SYNOPSIS
    u-desktop 构建脚本
.PARAMETER Pack
    打包为 zip（含 WebView2 bootstrapper）
#>
param(
    [switch]$Pack
)

$ErrorActionPreference = "Stop"
$project = "u-desktop"
$buildDir = "dist"

# 构建 Web UI
Write-Host "=== 构建 Web UI ===" -ForegroundColor Cyan
Push-Location web-ui
npm ci --prefer-offline
npm run build
if ($LASTEXITCODE -ne 0) { Write-Host "Web UI 构建失败" -ForegroundColor Red; exit 1 }
Pop-Location

# 清理
if (Test-Path $buildDir) { Remove-Item $buildDir -Recurse -Force }
New-Item -ItemType Directory -Force -Path $buildDir | Out-Null

# 版本号
$gitHash = git rev-parse --short HEAD
$version = "$(Get-Date -Format 'yyyyMMdd').$gitHash"
Write-Host "=== 构建 $project v$version ===" -ForegroundColor Cyan

# 构建 updater.exe（先编译，主程序需要 embed）
Write-Host "=== 构建 updater ===" -ForegroundColor Cyan
Push-Location updater
go build -ldflags="-s -w -H windowsgui" -o updater.exe .
if ($LASTEXITCODE -ne 0) { Write-Host "updater 构建失败" -ForegroundColor Red; exit 1 }
Pop-Location
Copy-Item "updater/updater.exe" "updater.exe" -Force
Write-Host "updater.exe 已复制到根目录" -ForegroundColor Green

# 构建（隐藏控制台窗口）
$env:GOOS = "windows"
$env:GOARCH = "amd64"
go build -ldflags="-s -w -H windowsgui -X main.version=$version" -o "$buildDir/$project.exe" .
if ($LASTEXITCODE -ne 0) { Write-Host "构建失败" -ForegroundColor Red; exit 1 }

$sizeBefore = [math]::Round((Get-Item "$buildDir/$project.exe").Length / 1MB, 1)
Write-Host "构建完成: $buildDir/$project.exe ($sizeBefore MB)" -ForegroundColor Green

# UPX 压缩
if (Get-Command upx -ErrorAction SilentlyContinue) {
    Write-Host "UPX 压缩中..." -ForegroundColor Yellow
    upx --best "$buildDir/$project.exe"
    $sizeAfter = [math]::Round((Get-Item "$buildDir/$project.exe").Length / 1MB, 1)
    Write-Host "UPX 完成: $sizeBefore MB -> $sizeAfter MB" -ForegroundColor Green
} else {
    Write-Host "UPX 未安装，跳过压缩" -ForegroundColor Yellow
}

if (-not $Pack) { exit 0 }

# --- 打包 ---
$packDir = "$buildDir\$project-win10-amd64"
if (Test-Path $packDir) { Remove-Item $packDir -Recurse -Force }
New-Item -ItemType Directory -Force -Path $packDir | Out-Null

# 复制 exe
Copy-Item "$buildDir\$project.exe" $packDir

# 下载 WebView2 bootstrapper
$bootstrapper = "$packDir\MicrosoftEdgeWebview2Setup.exe"
Write-Host "下载 WebView2 bootstrapper..." -ForegroundColor Yellow
Invoke-WebRequest -Uri "https://go.microsoft.com/fwlink/p/?LinkId=2124703" -OutFile $bootstrapper -UseBasicParsing

# 写入安装说明
@"
u-desktop v$version

== 首次运行（Windows 10）==
如果程序无法启动，请先运行 MicrosoftEdgeWebview2Setup.exe 安装 WebView2 运行时。
Windows 11 无需安装，直接运行 $project.exe 即可。
"@ | Out-File "$packDir\README.txt" -Encoding UTF8

# 打包 zip
$zipName = "$project-win10-amd64-v$version.zip"
Compress-Archive -Path $packDir -DestinationPath "$buildDir\$zipName" -Force
Write-Host "打包完成: $buildDir\$zipName" -ForegroundColor Green

# 清理临时目录
Remove-Item $packDir -Recurse -Force
