param(
  [string]$SmokeOutput
)

$ErrorActionPreference = 'Stop'

$repoRoot = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path
$sourcePath = Join-Path $repoRoot 'build\scripts\project-routing-smoke.ts'
$tempRoot = Join-Path $repoRoot '.tmp\project-routing-smoke'
$compileRoot = Join-Path $tempRoot 'compiled'
$entryPath = Join-Path $compileRoot 'build\scripts\project-routing-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 "Project routing 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 project-routing smoke with local TypeScript'
corepack @compileArgs
if ($LASTEXITCODE -ne 0) {
  exit $LASTEXITCODE
}

if (-not (Test-Path $entryPath)) {
  throw "Project routing 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 project-routing smoke'
node $entryPath $resolvedResultPath
if ($LASTEXITCODE -ne 0) {
  exit $LASTEXITCODE
}

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