param(
  [int]$SmokePort = 4318,
  [string]$SmokeToken = 'smoke-token',
  [string]$BaseOutputDir,
  [int]$TimeoutSeconds = 180
)

$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 $BaseOutputDir) {
  $BaseOutputDir = Join-Path $repoRoot '.tmp\settings-smoke'
}

$BaseOutputDir = [System.IO.Path]::GetFullPath($BaseOutputDir)
$userDataPath = Join-Path $BaseOutputDir 'user-data'
$logsPath = Join-Path $BaseOutputDir 'logs'
$smokeOutput = Join-Path $BaseOutputDir 'result.json'
$electronSmokeScript = Join-Path $repoRoot 'build\scripts\electron-smoke.ps1'

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

Invoke-ElectronSmokeWithRetry -ScriptPath $electronSmokeScript -Label 'settings smoke' -ArgumentList @(
  '-SmokeOutput', $smokeOutput,
  '-SmokePort', $SmokePort,
  '-SmokeToken', $SmokeToken,
  '-UserDataPath', $userDataPath,
  '-LogsPath', $logsPath,
  '-RuntimeMode', 'bundled-runtime',
  '-SmokeViewMode', 'settings',
  '-TimeoutSeconds', $TimeoutSeconds
)
