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

$ErrorActionPreference = 'Stop'

function Invoke-ElectronSmokeWithRetry {
  param(
    [string]$ScriptPath,
    [string]$Label,
    [string[]]$ArgumentList,
    [int]$MaxAttempts = 2
  )

  for ($attempt = 1; $attempt -le $MaxAttempts; $attempt += 1) {
    powershell -ExecutionPolicy Bypass -File $ScriptPath @ArgumentList
    if ($LASTEXITCODE -eq 0) {
      return
    }
    if ($attempt -ge $MaxAttempts) {
      exit $LASTEXITCODE
    }
    Write-Warning "$Label failed on attempt $attempt. Retrying..."
    Start-Sleep -Seconds 2
  }
}

$repoRoot = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path
if (-not $SmokeOutput) {
  $SmokeOutput = Join-Path $repoRoot '.tmp\workspace-entry-smoke\result.json'
}
if (-not $UserDataPath) {
  $UserDataPath = Join-Path $repoRoot '.tmp\workspace-entry-smoke\user-data'
}
if (-not $LogsPath) {
  $LogsPath = Join-Path $repoRoot '.tmp\workspace-entry-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
  }
}

Invoke-ElectronSmokeWithRetry -ScriptPath (Join-Path $repoRoot 'build\scripts\electron-smoke.ps1') -Label 'workspace-entry smoke' -ArgumentList @(
  '-SmokeOutput', $SmokeOutput,
  '-UserDataPath', $UserDataPath,
  '-LogsPath', $LogsPath,
  '-RuntimeMode', 'bundled-runtime',
  '-ExpectBundledRuntime',
  '-PrepareWorkspaceEntryFixture',
  '-ExpectWorkspaceEntry',
  '-WorkspaceProjectId', 'workspace-entry-smoke',
  '-WorkspaceProjectName', 'Workspace Entry Smoke',
  '-SmokePrompt', 'Describe the current project root and confirm workspace execution.',
  '-SmokeSkillId', '__workspace_entry_disabled__',
  '-TimeoutSeconds', $TimeoutSeconds
)
exit 0
