# Build a ZIP package for offline local-server deployment.
param(
    [string]$OutputDir = "",
    [string]$Version = ""
)

$ErrorActionPreference = "Stop"
$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$root = (Resolve-Path (Join-Path $scriptDir "..\..")).Path

if (-not $Version) {
    $verFile = Join-Path $root "version.txt"
    if (Test-Path $verFile) { $Version = (Get-Content $verFile -Raw).Trim() }
    if (-not $Version) { $Version = (Get-Date -Format "yyyyMMdd") }
}

if (-not $OutputDir) { $OutputDir = Join-Path $root "dist" }
New-Item -ItemType Directory -Force -Path $OutputDir | Out-Null

$staging = Join-Path $env:TEMP "cnperp-local-staging-$Version"
if (Test-Path $staging) { Remove-Item $staging -Recurse -Force }
New-Item -ItemType Directory -Path $staging | Out-Null

$include = @(
    "app", "deploy", "migrations", "scripts", "requirements.txt", "version.txt"
)
foreach ($item in $include) {
    $src = Join-Path $root $item
    if (Test-Path $src) {
        Copy-Item -Path $src -Destination (Join-Path $staging $item) -Recurse -Force
    }
}

$zipName = "cnperp-local-install-$Version.zip"
$zipPath = Join-Path $OutputDir $zipName
if (Test-Path $zipPath) { Remove-Item $zipPath -Force }
Compress-Archive -Path (Join-Path $staging "*") -DestinationPath $zipPath -Force
Remove-Item $staging -Recurse -Force

Write-Host "Created: $zipPath" -ForegroundColor Green
Write-Host "Customer: extract ZIP, then run deploy\local-server\Install-CNPERP-Local.ps1 as Administrator"
