# Dragonflight Premiere panel — Windows installer build
#
# Parses the version from ../CSXS/manifest.xml and hands it to ISCC.exe.
# Requires Inno Setup 6 on PATH (winget install JRSoftware.InnoSetup).
#
# Usage:  pwsh -File build-installer.ps1

$ErrorActionPreference = 'Stop'
Set-Location $PSScriptRoot

$manifestPath = Join-Path $PSScriptRoot '..\CSXS\manifest.xml'
if (-not (Test-Path $manifestPath)) {
    throw "Manifest not found at $manifestPath"
}
# Regex over XML because [xml] is strict about things Adobe CEP tolerates.
# Accept either the element form (<ExtensionBundleVersion>X.Y.Z</...>) or the
# attribute form (ExtensionBundleVersion="X.Y.Z") used by CSXS 7.0+ manifests.
$manifestRaw = Get-Content -Raw -Path $manifestPath
$version = $null
if ($manifestRaw -match '<ExtensionBundleVersion>([^<]+)</ExtensionBundleVersion>') {
    $version = $Matches[1].Trim()
} elseif ($manifestRaw -match 'ExtensionBundleVersion\s*=\s*"([^"]+)"') {
    $version = $Matches[1].Trim()
}
if (-not $version) {
    throw 'Could not read ExtensionBundleVersion from manifest.xml'
}
Write-Host "Dragonflight Premiere panel - Windows installer build v$version"

$iscc = Get-Command 'ISCC.exe' -ErrorAction SilentlyContinue
if (-not $iscc) {
    # Common Inno Setup 6 install locations. winget user-scope drops it in
    # %LOCALAPPDATA%\Programs; machine-wide installs land in Program Files.
    $fallbacks = @(
        "${env:LOCALAPPDATA}\Programs\Inno Setup 6\ISCC.exe",
        "${env:ProgramFiles(x86)}\Inno Setup 6\ISCC.exe",
        "${env:ProgramFiles}\Inno Setup 6\ISCC.exe"
    )
    foreach ($p in $fallbacks) {
        if (Test-Path $p) { $iscc = Get-Command $p; break }
    }
    if (-not $iscc) {
        throw "ISCC.exe not found. Install Inno Setup 6: winget install JRSoftware.InnoSetup"
    }
}

$distDir = Join-Path $PSScriptRoot 'dist'
New-Item -ItemType Directory -Force -Path $distDir | Out-Null

& $iscc.Source "/DMyAppVersion=$version" "installer.iss"
if ($LASTEXITCODE -ne 0) {
    throw "ISCC failed with exit code $LASTEXITCODE"
}

$output = Join-Path $distDir "dragonflight-premiere-panel-$version-windows-setup.exe"
if (-not (Test-Path $output)) {
    throw "Expected output not found: $output"
}
$size = [math]::Round((Get-Item $output).Length / 1KB, 1)
Write-Host "Built $output ($size KB)"
