param(
  [string]$OutputPath = (Join-Path (Join-Path (Split-Path -Parent $PSScriptRoot) 'dist') 'sanglive-enduser.zip'),
  [switch]$ExcludeNodeModules
)

$ErrorActionPreference = 'Stop'

$root = Split-Path -Parent $PSScriptRoot

$outputFullPath = [System.IO.Path]::GetFullPath($OutputPath)
$outputDir = Split-Path -Parent $outputFullPath
$tempRoot = Join-Path $env:TEMP ('sanglive-package-' + [guid]::NewGuid().ToString('N'))
$packageRoot = Join-Path $tempRoot 'S-Live'

New-Item -ItemType Directory -Force -Path $outputDir | Out-Null
New-Item -ItemType Directory -Force -Path $packageRoot | Out-Null

try {
  $excludeDirs = @('.git', '.runtime', '.cloud-runtime', 'logs', 'dist')
  if ($ExcludeNodeModules) { $excludeDirs += 'node_modules' }
  $excludeFiles = @('.env', '.env.local', '.env.production', '.tokens.json')
  $excludeExtensions = @('.log')

  Get-ChildItem -LiteralPath $root -Force | ForEach-Object {
    if ($excludeDirs -contains $_.Name -or $excludeFiles -contains $_.Name) { return }
    if (-not $_.PSIsContainer -and $excludeExtensions -contains $_.Extension) { return }
    Copy-Item -LiteralPath $_.FullName -Destination $packageRoot -Recurse -Force
  }

  $cloudBackend = Join-Path $packageRoot 'server\cloud-oauth.js'
  if (Test-Path $cloudBackend) {
    Remove-Item -LiteralPath $cloudBackend -Force
  }

  if (Test-Path $outputFullPath) {
    Remove-Item -LiteralPath $outputFullPath -Force
  }

  Compress-Archive -Path (Join-Path $packageRoot '*') -DestinationPath $outputFullPath -Force
  Write-Host "Created $outputFullPath"
} finally {
  Remove-Item -LiteralPath $tempRoot -Recurse -Force -ErrorAction SilentlyContinue
}
