param(
  [int]$GatewayPort = 18889,
  [string]$GatewayToken = 'qjc-bundled-runtime-token',
  [string]$SmokeOutput,
  [string]$UserDataPath,
  [string]$LogsPath,
  [int]$TimeoutSeconds = 90,
  [switch]$SkipMaterializeRuntime
)

$ErrorActionPreference = 'Stop'

function Write-Utf8File {
  param([string]$filePath, [string]$content)
  $encoding = New-Object System.Text.UTF8Encoding($false)
  [System.IO.File]::WriteAllText($filePath, $content, $encoding)
}

$repoRoot = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path
if (-not $SmokeOutput) {
  $SmokeOutput = Join-Path $repoRoot '.tmp\bundled-runtime-smoke\result.json'
}
if (-not $UserDataPath) {
  $UserDataPath = Join-Path $repoRoot '.tmp\bundled-runtime-smoke\user-data'
}
if (-not $LogsPath) {
  $LogsPath = Join-Path $repoRoot '.tmp\bundled-runtime-smoke\logs'
}

$BaseOutputDir = [System.IO.Path]::GetFullPath((Split-Path $SmokeOutput -Parent))
$userDataPath = [System.IO.Path]::GetFullPath($UserDataPath)
$logsPath = [System.IO.Path]::GetFullPath($LogsPath)
$bundleSourceRoot = Join-Path $BaseOutputDir 'bundle-src'
$bundleRoot = Join-Path $bundleSourceRoot 'bundled-runtime-smoke'
$bundleZipPath = Join-Path $BaseOutputDir 'bundled-runtime-smoke.zip'
$bundleFileName = 'bundled-runtime-smoke.zip'
$bundleProjectId = 'bundled-runtime-smoke'
$bundleProjectName = ''
$bundleSkillId = 'bundled-runtime-smoke-skill'
$bundleConfigVersion = '2026-04-03T03:55:00.000Z'
$bundleReadmeMarker = 'Bundled runtime smoke bundle marker.'

if (Test-Path $BaseOutputDir) {
  Remove-Item $BaseOutputDir -Recurse -Force -ErrorAction SilentlyContinue
}
New-Item -ItemType Directory -Force -Path $BaseOutputDir, $bundleRoot, $userDataPath, $logsPath | Out-Null

$bundleProjectJson = [ordered]@{
  id = $bundleProjectId
  name = $bundleProjectName
  description = 'Remote bundle fixture for bundled runtime smoke.'
  version = '1.0.0'
}
$bundleReadme = @(
  '# Bundled Runtime Smoke',
  '',
  'This bundle validates that bundled runtime startup can sync a zip-backed project bundle.',
  $bundleReadmeMarker
) -join [Environment]::NewLine
$bundleAgent = @(
  '# Bundled Runtime Smoke',
  '',
  'This project is used to validate remote zip bundle sync during packaged desktop startup.'
) -join [Environment]::NewLine

$utf8NoBom = New-Object System.Text.UTF8Encoding($false)
Write-Utf8File (Join-Path $bundleRoot 'project.json') ($bundleProjectJson | ConvertTo-Json -Depth 5)
Write-Utf8File (Join-Path $bundleRoot 'README.md') $bundleReadme
Write-Utf8File (Join-Path $bundleRoot 'AGENT.md') $bundleAgent
New-Item -ItemType Directory -Force -Path (Join-Path $bundleRoot 'memory') | Out-Null
Write-Utf8File (Join-Path $bundleRoot 'memory\summary.md') 'Bundled runtime smoke memory marker.'

if (Test-Path $bundleZipPath) {
  Remove-Item $bundleZipPath -Force -ErrorAction SilentlyContinue
}
Compress-Archive -Path (Join-Path $bundleSourceRoot '*') -DestinationPath $bundleZipPath -Force

if (-not $SkipMaterializeRuntime) {
  Write-Host "Materializing bundled runtime payload on port $GatewayPort"
  powershell -ExecutionPolicy Bypass -File (Join-Path $repoRoot 'build\scripts\materialize-runtime-payload.ps1') -GatewayPort $GatewayPort -GatewayToken $GatewayToken
  if ($LASTEXITCODE -ne 0) {
    exit $LASTEXITCODE
  }
}

$env:QJCLAW_SMOKE_BUNDLE_ZIP_PATH = $bundleZipPath
$env:QJCLAW_SMOKE_BUNDLE_FILE_NAME = $bundleFileName
$env:QJCLAW_SMOKE_BUNDLE_SKILL_ID = $bundleSkillId
$env:QJCLAW_SMOKE_BUNDLE_SKILL_TITLE = 'Bundled Runtime Smoke Skill'
$env:QJCLAW_SMOKE_BUNDLE_SKILL_DESCRIPTION = 'Remote zip-backed bundle for bundled runtime smoke validation.'
$env:QJCLAW_SMOKE_BUNDLE_CONFIG_VERSION = $bundleConfigVersion

try {
  powershell -ExecutionPolicy Bypass -File (Join-Path $repoRoot 'build\scripts\electron-smoke.ps1') -SmokeOutput $SmokeOutput -UserDataPath $UserDataPath -LogsPath $LogsPath -RuntimeMode 'bundled-runtime' -ExpectBundledRuntime -ExpectRemoteBundle -WorkspaceProjectId $bundleProjectId -SmokePrompt 'Describe the current project root and confirm bundled runtime smoke bundle execution.' -SmokeSkillId '__bundled_runtime_smoke_disabled__' -ExpectedBundleSourceUrl "http://127.0.0.1:$GatewayPort/downloads/$bundleFileName" -ExpectedBundleConfigVersion $bundleConfigVersion -ExpectedBundleFileName $bundleFileName -ExpectedBundleSkillId $bundleSkillId -ExpectedReadmeMarker $bundleReadmeMarker -TimeoutSeconds $TimeoutSeconds
  exit $LASTEXITCODE
} finally {
  Remove-Item Env:QJCLAW_SMOKE_BUNDLE_ZIP_PATH -ErrorAction SilentlyContinue
  Remove-Item Env:QJCLAW_SMOKE_BUNDLE_FILE_NAME -ErrorAction SilentlyContinue
  Remove-Item Env:QJCLAW_SMOKE_BUNDLE_SKILL_ID -ErrorAction SilentlyContinue
  Remove-Item Env:QJCLAW_SMOKE_BUNDLE_SKILL_TITLE -ErrorAction SilentlyContinue
  Remove-Item Env:QJCLAW_SMOKE_BUNDLE_SKILL_DESCRIPTION -ErrorAction SilentlyContinue
  Remove-Item Env:QJCLAW_SMOKE_BUNDLE_CONFIG_VERSION -ErrorAction SilentlyContinue
}
