<#
.SYNOPSIS
  Packages the WCAHT Wallet extension for Firefox (MV2).

.DESCRIPTION
  1. Copies all extension files to a temp staging folder.
  2. Replaces manifest.json with manifest-firefox.json.
  3. Creates wcaht-wallet-firefox.zip ready for Firefox Add-ons.

.USAGE
  .\build-firefox.ps1
  Output: dist\wcaht-wallet-firefox.zip
#>

$ErrorActionPreference = 'Stop'

$ExtRoot  = $PSScriptRoot
$Staging  = Join-Path $ExtRoot 'dist\_firefox_staging'
$OutDir   = Join-Path $ExtRoot 'dist'
$OutZip   = Join-Path $OutDir  'wcaht-wallet-firefox.zip'

Write-Host "`n=== WCAHT Wallet — Firefox build ===" -ForegroundColor Cyan

# --- Clean staging ---
if (Test-Path $Staging) { Remove-Item $Staging -Recurse -Force }
New-Item -ItemType Directory -Path $Staging | Out-Null

# --- Copy all extension files (excluding build artefacts and the staging dir itself) ---
$Exclude = @('dist', '.git', 'node_modules', '*.ps1')
Get-ChildItem $ExtRoot -Exclude $Exclude | Copy-Item -Destination $Staging -Recurse -Force
Write-Host "Copied extension files to staging."

# --- Swap in the Firefox manifest ---
Copy-Item (Join-Path $ExtRoot 'manifest-firefox.json') `
          (Join-Path $Staging 'manifest.json') -Force
Write-Host "Replaced manifest.json with manifest-firefox.json."

# --- Remove the Chrome-only manifest-firefox.json from the zip ---
$ffManifestInStage = Join-Path $Staging 'manifest-firefox.json'
if (Test-Path $ffManifestInStage) { Remove-Item $ffManifestInStage -Force }

# --- Zip ---
if (Test-Path $OutZip) { Remove-Item $OutZip -Force }
if (-not (Test-Path $OutDir)) { New-Item -ItemType Directory -Path $OutDir | Out-Null }

Add-Type -AssemblyName System.IO.Compression.FileSystem
[System.IO.Compression.ZipFile]::CreateFromDirectory($Staging, $OutZip)

Write-Host "Created: $OutZip" -ForegroundColor Green

# --- Cleanup staging ---
Remove-Item $Staging -Recurse -Force

Write-Host @"

Next steps (Firefox):
  1. Open Firefox → about:debugging → This Firefox → Load Temporary Add-on
  2. Browse to: $OutZip  (or point to dist\_firefox_staging\manifest.json before cleanup)
  3. To publish: sign the .zip at https://addons.mozilla.org/developers/

Next steps (Chrome / Edge):
  - Load unpacked from: $ExtRoot  (uses manifest.json as-is, MV3)
"@ -ForegroundColor Cyan
