param(
  [switch]$Install
)

$ErrorActionPreference = 'Stop'

$BootstrapRoot = Split-Path -Parent $MyInvocation.MyCommand.Path
$SourceZip = Join-Path $BootstrapRoot 'source\qne-node-v00023-windows-ui-source.zip'
$ExtractRoot = Join-Path $env:USERPROFILE 'QNEDEV\qne-node-v00023-windows-ui-source'
$ProjectRoot = Join-Path $ExtractRoot 'qne-node-v00023'
$SetupScript = Join-Path $ProjectRoot 'scripts\setup-windows-codex-toolchain.ps1'

Write-Host 'QNE Windows toolchain bootstrap v00001'
Write-Host "bootstrap_root = $BootstrapRoot"
Write-Host "source_zip = $SourceZip"
Write-Host "extract_root = $ExtractRoot"

if (!(Test-Path $SourceZip)) {
  throw "Bundled source zip missing: $SourceZip"
}

if (!(Test-Path $ProjectRoot) -or !(Test-Path $SetupScript)) {
  Remove-Item -Recurse -Force $ExtractRoot -ErrorAction SilentlyContinue
  New-Item -ItemType Directory -Force -Path $ExtractRoot | Out-Null
  Expand-Archive -Force -Path $SourceZip -DestinationPath $ExtractRoot
}

if (!(Test-Path $SetupScript)) {
  throw "setup script missing after extract: $SetupScript"
}

Set-Location $ProjectRoot
if ($Install) {
  powershell.exe -NoProfile -ExecutionPolicy Bypass -File $SetupScript -Install
} else {
  powershell.exe -NoProfile -ExecutionPolicy Bypass -File $SetupScript
}
