<#
.SYNOPSIS
  Builds both the VSCode extension (.vsix) and the standalone Windows exe.
  Both artifacts land in dist/.

.EXAMPLE
  .\build.ps1
  .\build.ps1 -Standalone   # Skip the extension; build only the exe
  .\build.ps1 -Extension    # Skip the standalone; build only the .vsix
#>
[CmdletBinding()]
param(
  [switch]$Extension,
  [switch]$Standalone
)

$ErrorActionPreference = "Stop"
$repoRoot = Split-Path -Parent $MyInvocation.MyCommand.Path
Set-Location $repoRoot

# If neither was specified, build both.
if (-not $Extension -and -not $Standalone) {
  $Extension = $true
  $Standalone = $true
}

$distDir = Join-Path $repoRoot "dist"
if (Test-Path $distDir) {
  Remove-Item -Path (Join-Path $distDir "*") -Recurse -Force
}
New-Item -ItemType Directory -Path $distDir -Force | Out-Null

$pkg = Get-Content (Join-Path $repoRoot "package.json") -Raw | ConvertFrom-Json
$version = $pkg.version

function Write-Step($msg) {
  Write-Host ""
  Write-Host "==> $msg" -ForegroundColor Cyan
}

function Get-FileSize($path) {
  if (-not (Test-Path $path)) { return $null }
  $bytes = (Get-Item $path).Length
  if ($bytes -ge 1MB) { return "{0:N2} MB" -f ($bytes / 1MB) }
  if ($bytes -ge 1KB) { return "{0:N1} KB" -f ($bytes / 1KB) }
  return "$bytes B"
}

# Ensure Go is on PATH (winget install doesn't update current session)
if (-not (Get-Command go -ErrorAction SilentlyContinue)) {
  $goBin = "C:\Program Files\Go\bin"
  if (Test-Path "$goBin\go.exe") {
    $env:Path = "$goBin;$env:Path"
  } else {
    Write-Error "go not found on PATH. Install Go from https://go.dev/dl/"
    exit 1
  }
}

$summary = @()

# ----------------------------------------------------------------------
# VSCode extension -> .vsix
# ----------------------------------------------------------------------
if ($Extension) {
  Write-Step "Building VSCode extension"
  if (-not (Test-Path "node_modules")) {
    Write-Host "  node_modules missing - running npm install" -ForegroundColor Yellow
    npm install
    if ($LASTEXITCODE -ne 0) { Write-Error "npm install failed"; exit 1 }
  }
  npm run compile
  if ($LASTEXITCODE -ne 0) { Write-Error "tsc compile failed"; exit 1 }

  Write-Step "Packaging .vsix -> dist/"
  $vsixTargetDir = $distDir
  if (Get-Command vsce -ErrorAction SilentlyContinue) {
    vsce package --out $vsixTargetDir
  } else {
    Write-Host "  vsce not found - using npx @vscode/vsce" -ForegroundColor Yellow
    npx --yes @vscode/vsce package --out $vsixTargetDir
  }
  if ($LASTEXITCODE -ne 0) { Write-Error "vsce package failed"; exit 1 }

  $vsix = Get-ChildItem -Path $distDir -Filter "*.vsix" | Sort-Object LastWriteTime -Descending | Select-Object -First 1
  if ($vsix) {
    $summary += [pscustomobject]@{
      Artifact = $vsix.Name
      Path     = "dist\$($vsix.Name)"
      Size     = Get-FileSize $vsix.FullName
    }
  }
}

# ----------------------------------------------------------------------
# Standalone Windows exe -> dist/hpl-toolbox.exe
# ----------------------------------------------------------------------
if ($Standalone) {
  Write-Step "Building standalone exe -> dist/"
  Push-Location (Join-Path $repoRoot "standalone")
  try {
    # If rsrc.syso is missing (e.g. fresh clone before icon embedding), regenerate.
    if (-not (Test-Path "rsrc.syso") -and (Test-Path "hpl.ico")) {
      if (Get-Command rsrc -ErrorAction SilentlyContinue) {
        Write-Host "  Regenerating rsrc.syso" -ForegroundColor Yellow
        rsrc -ico hpl.ico -o rsrc.syso
      } else {
        Write-Host "  rsrc tool missing - exe will build without embedded icon" -ForegroundColor Yellow
        Write-Host "  (install with: go install github.com/akavel/rsrc@latest)" -ForegroundColor Yellow
      }
    }

    $exeName = "hpl-toolbox-$version.exe"
    $exeOut = Join-Path $distDir $exeName
    $embeddedReadme = Join-Path (Get-Location) "README.md"
    Copy-Item -Path (Join-Path $repoRoot "README.md") -Destination $embeddedReadme -Force
    try {
      go build -tags release -ldflags="-s -w -H windowsgui -X main.AppVersion=$version" -trimpath -o $exeOut .
      if ($LASTEXITCODE -ne 0) { Write-Error "go build failed"; exit 1 }
    } finally {
      Remove-Item -Path $embeddedReadme -Force -ErrorAction SilentlyContinue
    }

    $summary += [pscustomobject]@{
      Artifact = $exeName
      Path     = "dist\$exeName"
      Size     = Get-FileSize $exeOut
    }
  } finally {
    Pop-Location
  }
}

# ----------------------------------------------------------------------
# Summary
# ----------------------------------------------------------------------
Write-Step "Build complete"
$summary | Format-Table -AutoSize | Out-Host
