$ErrorActionPreference = "Stop"

$source = Split-Path -Parent (Split-Path -Parent $PSScriptRoot)
$delivery = Join-Path (Split-Path -Parent $source) "delivery-build"
$staging = Join-Path $delivery "fashion-ai-design-exe-standard"
$zip = Join-Path $delivery "fashion-ai-design-exe-standard.zip"

Push-Location $source
try {
  npm.cmd run build
  npm.cmd run skills:bundle
} finally {
  Pop-Location
}

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

Copy-Item -LiteralPath (Join-Path $source ".next\standalone") -Destination (Join-Path $staging "standalone") -Recurse -Force
New-Item -ItemType Directory -Path (Join-Path $staging "standalone\.next") -Force | Out-Null
Copy-Item -LiteralPath (Join-Path $source ".next\static") -Destination (Join-Path $staging "standalone\.next\static") -Recurse -Force

$nodeExe = (Get-Command node.exe -ErrorAction Stop).Source
Copy-Item -LiteralPath $nodeExe -Destination (Join-Path $staging "node.exe") -Force

$items = @(
  "tools\exe",
  ".env.example",
  "package.json",
  "README-CUST.MD",
  "DEPLOYMENT.md"
)

foreach ($item in $items) {
  $src = Join-Path $source $item
  if (!(Test-Path $src)) { throw "Missing required package item: $item" }
  Copy-Item -LiteralPath $src -Destination (Join-Path $staging $item) -Recurse -Force
}

Copy-Item -LiteralPath (Join-Path $source "public") -Destination (Join-Path $staging "standalone\public") -Recurse -Force
Copy-Item -LiteralPath (Join-Path $source "runtime-assets") -Destination (Join-Path $staging "standalone\runtime-assets") -Recurse -Force

$notes = @(
  "Fashion AI Design Studio EXE-standard delivery scaffold.",
  "",
  "Install service:",
  "  powershell -ExecutionPolicy Bypass -File tools\exe\install-windows-service.ps1",
  "",
  "Tray control:",
  "  powershell -ExecutionPolicy Bypass -File tools\exe\tray-control.ps1",
  "",
  "Runtime data is stored under C:\ProgramData\FashionAIDesignStudio."
)
Set-Content -LiteralPath (Join-Path $staging "EXE-PACKAGE-NOTES.txt") -Value $notes -Encoding UTF8

if (Test-Path $zip) {
  Remove-Item -LiteralPath $zip -Force
}
Compress-Archive -Path $staging -DestinationPath $zip -CompressionLevel Optimal
Write-Host "[Done] EXE-standard package scaffold created: $zip"
