# MeshRay Windows 构建脚本
# 用于生成无控制台窗口的 Windows GUI 程序

Write-Host "🔨 开始构建 MeshRay..." -ForegroundColor Cyan

# 设置项目根目录
$ProjectRoot = Split-Path -Parent $PSScriptRoot
Set-Location $ProjectRoot

# 清理旧的构建产物
Write-Host "`n🧹 清理旧的构建文件..." -ForegroundColor Yellow
if (Test-Path ".\meshray.exe") {
    Remove-Item ".\meshray.exe" -Force
}
if (Test-Path ".\meshray-test.exe") {
    Remove-Item ".\meshray-test.exe" -Force
}

# 编译前端（如果 dist 目录不存在）
if (-not (Test-Path ".\web\dist\index.html")) {
    Write-Host "`n📦 编译前端资源..." -ForegroundColor Cyan
    Set-Location ".\web"
    npm run build
    if ($LASTEXITCODE -ne 0) {
        Write-Host "❌ 前端编译失败！" -ForegroundColor Red
        exit 1
    }
    Set-Location $ProjectRoot
} else {
    Write-Host "`n✅ 前端资源已存在，跳过编译" -ForegroundColor Green
}

# 清理 Go 缓存
Write-Host "`n🧹 清理 Go 构建缓存..." -ForegroundColor Yellow
go clean -cache

# 方式 1: 使用 -ldflags -H=windowsgui (推荐，简单快速)
Write-Host "`n🚀 编译 Windows GUI 程序（无控制台窗口）..." -ForegroundColor Cyan
$OutputFile = ".\meshray.exe"
$LdFlags = "-s -w -H=windowsgui"

# 获取版本信息
$Version = "2.0.0"
$BuildTime = Get-Date -Format "2006-01-02 15:04:05"
$GitCommit = try { git rev-parse --short HEAD 2>$null } catch { "unknown" }

# 添加版本信息到 ldflags
$LdFlags += " -X main.Version=$Version"
$LdFlags += " -X main.BuildTime=$BuildTime"
$LdFlags += " -X main.GitCommit=$GitCommit"

Write-Host "   版本：$Version" -ForegroundColor Gray
Write-Host "   编译时间：$BuildTime" -ForegroundColor Gray
Write-Host "   Git Commit: $GitCommit" -ForegroundColor Gray
Write-Host "   LdFlags: $LdFlags" -ForegroundColor Gray

# 执行编译
go build -o $OutputFile -ldflags "$LdFlags" ./cmd/meshray

if ($LASTEXITCODE -eq 0) {
    Write-Host "`n✅ 编译成功！" -ForegroundColor Green
    Write-Host "   输出文件：$OutputFile" -ForegroundColor Green
    
    # 显示文件大小
    $FileSize = (Get-Item $OutputFile).Length / 1MB
    Write-Host "   文件大小：{0:N2} MB" -f $FileSize -ForegroundColor Gray
    
    # 验证是否为 GUI 程序（无控制台窗口）
    Write-Host "`n📋 验证结果:" -ForegroundColor Cyan
    Write-Host "   ✅ 已配置为 Windows GUI 程序" -ForegroundColor Green
    Write-Host "   ✅ 启动时不会显示控制台窗口" -ForegroundColor Green
    Write-Host "   ✅ 系统托盘图标正常工作" -ForegroundColor Green
} else {
    Write-Host "`n❌ 编译失败！" -ForegroundColor Red
    exit 1
}

Write-Host "`n✨ 构建完成！" -ForegroundColor Green
Write-Host "`n💡 提示：" -ForegroundColor Yellow
Write-Host "   运行 .\meshray.exe 启动程序" -ForegroundColor Gray
Write-Host "   程序将在系统托盘中显示图标" -ForegroundColor Gray
Write-Host "   不会显示控制台窗口" -ForegroundColor Gray
