param(
  [string]$SmokeOutput
)

$ErrorActionPreference = 'Stop'

$repoRoot = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path
$sourcePath = Join-Path $repoRoot 'build\scripts\project-package-orchestrator-smoke.ts'
$tempRoot = Join-Path $repoRoot '.tmp\project-package-orchestrator-smoke'
$compileRoot = Join-Path $tempRoot 'compiled'
$entryPath = Join-Path $compileRoot 'build\scripts\project-package-orchestrator-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)
}

if (-not (Test-Path $sourcePath)) {
  throw "Project package orchestrator 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-package-orchestrator smoke with local TypeScript'
corepack @compileArgs
if ($LASTEXITCODE -ne 0) {
  exit $LASTEXITCODE
}

if (-not (Test-Path $entryPath)) {
  throw "Project package orchestrator smoke entry was not emitted: $entryPath"
}

$runtimeManagerDistSource = Join-Path $repoRoot 'packages\runtime-manager\dist'
$runtimeManagerDistTarget = Join-Path $compileRoot 'packages\runtime-manager\dist'
if (-not (Test-Path $runtimeManagerDistSource)) {
  throw "Runtime manager dist was not found: $runtimeManagerDistSource"
}
New-Item -ItemType Directory -Path (Split-Path $runtimeManagerDistTarget -Parent) -Force | Out-Null
Copy-Item -Path $runtimeManagerDistSource -Destination $runtimeManagerDistTarget -Recurse -Force

Write-Utf8File -FilePath $compilePackagePath -Content '{"type":"module"}'

Write-Host 'Running project-package-orchestrator smoke'
node $entryPath $resolvedResultPath
if ($LASTEXITCODE -ne 0) {
  exit $LASTEXITCODE
}

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

