param(
  [string]$SmokeOutput
)

$ErrorActionPreference = 'Stop'

$repoRoot = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path
$sourcePath = Join-Path $repoRoot 'build\scripts\project-bundle-churn-smoke.ts'
$tempRoot = Join-Path $repoRoot '.tmp\project-bundle-churn-smoke'
$compileRoot = Join-Path $tempRoot 'compiled'
$entryPath = Join-Path $compileRoot 'build\scripts\project-bundle-churn-smoke.js'
$compilePackagePath = Join-Path $compileRoot 'package.json'
$alphaRoot = Join-Path $tempRoot 'alpha-src'
$betaRootV1 = Join-Path $tempRoot 'beta-src-v1'
$betaRootV2 = Join-Path $tempRoot 'beta-src-v2'
$gammaRoot = Join-Path $tempRoot 'gamma-src'
$deltaRoot = Join-Path $tempRoot 'delta-src'
$alphaZipPath = Join-Path $tempRoot 'alpha.zip'
$betaZipPathV1 = Join-Path $tempRoot 'beta-v1.zip'
$betaZipPathV2 = Join-Path $tempRoot 'beta-v2.zip'
$gammaZipPath = Join-Path $tempRoot 'gamma.zip'
$deltaZipPath = Join-Path $tempRoot 'delta.zip'
$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-BundleFixture {
  param(
    [string]$Root,
    [string]$ProjectId,
    [string]$ProjectName,
    [string]$ReadmeMarker,
    [string]$SkillEntry,
    [string]$CronEntry
  )

  if (Test-Path $Root) {
    Remove-Item $Root -Recurse -Force
  }

  New-Item -ItemType Directory -Path (Join-Path (Join-Path $Root 'skills') $SkillEntry) -Force | Out-Null
  New-Item -ItemType Directory -Path (Join-Path $Root 'memory') -Force | Out-Null
  New-Item -ItemType Directory -Path (Join-Path $Root 'cron') -Force | Out-Null

  Write-Utf8File -FilePath (Join-Path $Root 'project.json') -Content (@{
    id = $ProjectId
    name = $ProjectName
    version = '1.0.0'
    description = 'Verifies multi-project bundle churn and inventory cleanup.'
  } | ConvertTo-Json -Depth 5)
  Write-Utf8File -FilePath (Join-Path $Root 'README.md') -Content ("# $ProjectName`n`n$ReadmeMarker")
  Write-Utf8File -FilePath (Join-Path $Root 'memory\summary.md') -Content ("$ProjectId memory")
  Write-Utf8File -FilePath (Join-Path (Join-Path (Join-Path $Root 'skills') $SkillEntry) 'SKILL.md') -Content ("# $ProjectName Skill")
  Write-Utf8File -FilePath (Join-Path (Join-Path $Root 'cron') $CronEntry) -Content ("$ProjectId cron")
}

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

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

foreach ($path in @($alphaRoot, $betaRootV1, $betaRootV2, $gammaRoot, $deltaRoot)) {
  if (Test-Path $path) {
    Remove-Item $path -Recurse -Force
  }
}
foreach ($path in @($alphaZipPath, $betaZipPathV1, $betaZipPathV2, $gammaZipPath, $deltaZipPath)) {
  if (Test-Path $path) {
    Remove-Item $path -Force
  }
}

New-BundleFixture -Root $alphaRoot -ProjectId 'bundle-churn-alpha' -ProjectName 'Bundle Churn Alpha' -ReadmeMarker 'Alpha stable variant.' -SkillEntry 'bundle-churn-alpha-skill' -CronEntry 'bundle-churn-alpha-task.txt'
New-BundleFixture -Root $betaRootV1 -ProjectId 'bundle-churn-beta' -ProjectName 'Bundle Churn Beta' -ReadmeMarker 'Beta variant V1' -SkillEntry 'bundle-churn-beta-skill-v1' -CronEntry 'bundle-churn-beta-task-v1.txt'
New-BundleFixture -Root $betaRootV2 -ProjectId 'bundle-churn-beta' -ProjectName 'Bundle Churn Beta' -ReadmeMarker 'Beta variant V2' -SkillEntry 'bundle-churn-beta-skill-v2' -CronEntry 'bundle-churn-beta-task-v2.txt'
New-BundleFixture -Root $gammaRoot -ProjectId 'bundle-churn-gamma' -ProjectName 'Bundle Churn Gamma' -ReadmeMarker 'Gamma removable variant.' -SkillEntry 'bundle-churn-gamma-skill' -CronEntry 'bundle-churn-gamma-task.txt'
New-BundleFixture -Root $deltaRoot -ProjectId 'bundle-churn-delta' -ProjectName 'Bundle Churn Delta' -ReadmeMarker 'Delta newly added variant.' -SkillEntry 'bundle-churn-delta-skill' -CronEntry 'bundle-churn-delta-task.txt'

Compress-Archive -Path (Join-Path $alphaRoot '*') -DestinationPath $alphaZipPath -Force
Compress-Archive -Path (Join-Path $betaRootV1 '*') -DestinationPath $betaZipPathV1 -Force
Compress-Archive -Path (Join-Path $betaRootV2 '*') -DestinationPath $betaZipPathV2 -Force
Compress-Archive -Path (Join-Path $gammaRoot '*') -DestinationPath $gammaZipPath -Force
Compress-Archive -Path (Join-Path $deltaRoot '*') -DestinationPath $deltaZipPath -Force

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

Write-Host 'Running project-bundle churn smoke'
node $entryPath $resolvedResultPath $alphaZipPath $betaZipPathV1 $betaZipPathV2 $gammaZipPath $deltaZipPath
if ($LASTEXITCODE -ne 0) {
  exit $LASTEXITCODE
}

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