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

$ErrorActionPreference = 'Stop'

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

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
  }
}

Remove-Item Env:QJCLAW_SMOKE_CLOUD_API_BASE_URL -ErrorAction SilentlyContinue
Remove-Item Env:QJCLAW_SMOKE_AUTH_TOKEN -ErrorAction SilentlyContinue
Remove-Item Env:QJCLAW_SMOKE_RUNTIME_CLOUD_API_KEY -ErrorAction SilentlyContinue

powershell -ExecutionPolicy Bypass -File (Join-Path $repoRoot 'build\scripts\electron-smoke.ps1') `
  -SmokeOutput $SmokeOutput `
  -UserDataPath $UserDataPath `
  -LogsPath $LogsPath `
  -RuntimeMode 'bundled-runtime' `
  -ExpectBundledRuntime `
  -StartupOnly `
  -TimeoutSeconds $TimeoutSeconds

exit $LASTEXITCODE
