# Build full Siraya Receipt Printing Agent (service bundle + Electron portable)
param(
  [string]$Version = "3.0.0"
)

$ErrorActionPreference = "Stop"
$Root = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent

Write-Host "=== Step 1: Service release payload ==="
& powershell -ExecutionPolicy Bypass -File (Join-Path $Root "installer\windows\build-release.ps1") -Version $Version

$ReleaseDir = Join-Path $Root "dist\release"
$BundleStaging = Join-Path $Root "dist\electron-service-bundle"
Write-Host "=== Step 1b: Stage Electron service bundle ==="
if (Test-Path $BundleStaging) { Remove-Item $BundleStaging -Recurse -Force }
Copy-Item $ReleaseDir $BundleStaging -Recurse -Force

Write-Host "=== Step 2: Electron desktop app ==="
Push-Location (Join-Path $Root "desktop")
try {
  if (-not (Test-Path "node_modules")) {
    npm install
  }
  npm run build:dir
} finally {
  Pop-Location
}

$AgentDir = Join-Path $Root "dist\agent"
$DesktopOut = Join-Path $Root "dist\desktop\win-unpacked"

if (Test-Path $AgentDir) { Remove-Item $AgentDir -Recurse -Force }
New-Item -ItemType Directory -Path $AgentDir -Force | Out-Null

if (Test-Path $DesktopOut) {
  Copy-Item (Join-Path $DesktopOut "*") $AgentDir -Recurse -Force
}

Copy-Item (Join-Path $ReleaseDir "payload") (Join-Path $AgentDir "service") -Recurse -Force
Copy-Item (Join-Path $ReleaseDir "install-from-folder.ps1") $AgentDir -Force
Copy-Item (Join-Path $ReleaseDir "Install.cmd") $AgentDir -Force -ErrorAction SilentlyContinue
Copy-Item (Join-Path $Root "installer\windows\create-desktop-shortcut.ps1") $AgentDir -Force

$exe = Get-ChildItem $AgentDir -Filter "SirayaPrinter.exe" -Recurse | Select-Object -First 1
if ($exe) {
  Copy-Item $exe.FullName (Join-Path $AgentDir "SirayaPrinter.exe") -Force
  try {
    & powershell -ExecutionPolicy Bypass -File (Join-Path $AgentDir "create-desktop-shortcut.ps1") -TargetPath $exe.FullName
  } catch {
    Write-Host "Note: run create-desktop-shortcut.ps1 on the register PC for a Desktop icon"
  }
}

@{
  version = $Version
  builtAt = (Get-Date).ToUniversalTime().ToString("o")
  entry   = "SirayaPrinter.exe"
  service = "service/payload/win-x64"
} | ConvertTo-Json | Set-Content (Join-Path $AgentDir "manifest.json") -Encoding UTF8

Write-Host "Agent folder ready at $AgentDir"
Write-Host "  Copy dist/agent/ to register PC and run SirayaPrinter.exe"
