# PowerShell script to build Wails client
$ErrorActionPreference = "Stop"

Write-Host "=============================================" -ForegroundColor Cyan
Write-Host "           BUILDING WAILS CLIENT             " -ForegroundColor Cyan
Write-Host "=============================================" -ForegroundColor Cyan

# Check if wails is installed
$wailsInstalled = $null -ne (Get-Command wails -ErrorAction SilentlyContinue)

if ($wailsInstalled) {
    Write-Host "[*] Found Wails CLI. Building via Wails..." -ForegroundColor Green
    try {
        wails build
        Write-Host "[+] Build completed successfully using Wails CLI!" -ForegroundColor Green
        exit 0
    } catch {
        Write-Host "[-] Wails build failed. Attempting manual fallback build..." -ForegroundColor Yellow
    }
} else {
    Write-Host "[!] Wails CLI not found. Falling back to manual build..." -ForegroundColor Yellow
}

# Check for Go
if ($null -eq (Get-Command go -ErrorAction SilentlyContinue)) {
    Write-Host "[!] Go is not installed or not in PATH." -ForegroundColor Red
    exit 1
}

# Check for npm
if ($null -eq (Get-Command npm -ErrorAction SilentlyContinue)) {
    Write-Host "[!] Node.js/npm is not installed or not in PATH." -ForegroundColor Red
    exit 1
}

# Step 1: Build Frontend
Write-Host "[*] Building frontend assets..." -ForegroundColor Cyan
Push-Location frontend

try {
    if (-not (Test-Path "node_modules")) {
        Write-Host "[*] node_modules not found. Running 'npm install'..." -ForegroundColor Cyan
        npm install
    }
    
    Write-Host "[*] Running 'npm run build'..." -ForegroundColor Cyan
    npm run build
} finally {
    Pop-Location
}

# Step 2: Build Backend Go binary
Write-Host "[*] Building Go application..." -ForegroundColor Cyan

try {
    # -H windowsgui: prevents console window from flashing on startup
    go build -ldflags="-s -w -H windowsgui" -o client.exe main.go app.go
    Write-Host "[+] Build completed successfully! Generated client.exe" -ForegroundColor Green
} catch {
    Write-Host "[-] Go build failed." -ForegroundColor Red
    exit 1
}
