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

$ErrorActionPreference = 'Stop'

$repoRoot = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path
$sourcePath = Join-Path $repoRoot 'build\scripts\default-chat-context-smoke.ts'
$tempRoot = Join-Path $repoRoot '.tmp\default-chat-smoke'
$compileRoot = Join-Path $tempRoot 'compiled'
$entryPath = Join-Path $compileRoot 'build\scripts\default-chat-context-smoke.js'
$compilePackagePath = Join-Path $compileRoot 'package.json'
$resolvedResultPath = if ($SmokeOutput) { [System.IO.Path]::GetFullPath($SmokeOutput) } else { Join-Path $tempRoot 'result.json' }

function Write-Utf8File {
  param([string]$FilePath, [string]$Content)
  $encoding = New-Object System.Text.UTF8Encoding $false
  [System.IO.Directory]::CreateDirectory([System.IO.Path]::GetDirectoryName($FilePath)) | Out-Null
  [System.IO.File]::WriteAllText($FilePath, $Content, $encoding)
}

function New-WorkspacePackageJunction {
  param(
    [string]$PackageName,
    [string]$PackagePath
  )

  if (-not (Test-Path $PackagePath)) {
    throw "Workspace package was not found: $PackagePath"
  }

  $nodeModulesRoot = Join-Path $compileRoot 'node_modules'
  $scopeRoot = Join-Path $nodeModulesRoot '@qjclaw'
  $linkPath = Join-Path $scopeRoot $PackageName
  New-Item -ItemType Directory -Path $scopeRoot -Force | Out-Null
  if (Test-Path $linkPath) {
    Remove-Item $linkPath -Recurse -Force
  }
  New-Item -ItemType Junction -Path $linkPath -Target $PackagePath | Out-Null
}

if (-not (Test-Path $sourcePath)) {
  throw "Default chat smoke source was not found: $sourcePath"
}

if (Test-Path $compileRoot) {
  Remove-Item $compileRoot -Recurse -Force
}
New-Item -ItemType Directory -Path $compileRoot -Force | Out-Null

$compileArgs = @(
  'pnpm',
  '--dir', (Join-Path $repoRoot 'apps\desktop'),
  'exec',
  'tsc',
  '--module', 'ES2022',
  '--moduleResolution', 'node',
  '--target', 'ES2022',
  '--lib', 'ES2022',
  '--types', 'node',
  '--esModuleInterop',
  '--allowSyntheticDefaultImports',
  '--skipLibCheck',
  '--outDir', $compileRoot,
  $sourcePath
)

Write-Host 'Compiling default-chat smoke with local TypeScript'
corepack @compileArgs
if ($LASTEXITCODE -ne 0) {
  exit $LASTEXITCODE
}

if (-not (Test-Path $entryPath)) {
  throw "Default chat smoke entry was not emitted: $entryPath"
}

Write-Utf8File -FilePath $compilePackagePath -Content '{"type":"module"}'
New-WorkspacePackageJunction -PackageName 'shared-types' -PackagePath (Join-Path $repoRoot 'packages\shared-types')

Write-Host 'Running default-chat smoke'
node $entryPath $resolvedResultPath
if ($LASTEXITCODE -ne 0) {
  exit $LASTEXITCODE
}

if (-not (Test-Path $resolvedResultPath)) {
  throw "Default chat smoke did not produce a result file: $resolvedResultPath"
}
