param(
    [string]$AppVersion = (Get-Date -Format "yyyy.MM.dd.HHmm")
)

$ErrorActionPreference = "Stop"

function Resolve-InnoCompiler {
    $command = Get-Command ISCC.exe -ErrorAction SilentlyContinue
    if ($command) {
        return $command.Source
    }

    $candidates = @()
    if (${env:ProgramFiles(x86)}) {
        $candidates += (Join-Path ${env:ProgramFiles(x86)} "Inno Setup 6\ISCC.exe")
    }
    if ($env:ProgramFiles) {
        $candidates += (Join-Path $env:ProgramFiles "Inno Setup 6\ISCC.exe")
    }
    if ($env:LOCALAPPDATA) {
        $candidates += (Join-Path $env:LOCALAPPDATA "Programs\Inno Setup 6\ISCC.exe")
        $candidates += (Join-Path $env:LOCALAPPDATA "Inno Setup 6\ISCC.exe")
    }

    foreach ($candidate in $candidates) {
        if ($candidate -and (Test-Path $candidate)) {
            return $candidate
        }
    }
    throw "ISCC.exe introuvable. Installer Inno Setup 6 puis relancer."
}

function Require-Path {
    param(
        [string]$PathValue,
        [string]$Label
    )
    if (-not (Test-Path $PathValue)) {
        throw "$Label introuvable: $PathValue"
    }
}

$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$ProjectRoot = (Resolve-Path (Join-Path $ScriptDir "..")).Path
$InstallerScriptPath = Join-Path $ProjectRoot "installer\Anonymisation.iss"
$PackageExePath = Join-Path $ProjectRoot "release\Anonymisation-Windows\Anonymisation.exe"
$InstallerPath = Join-Path $ProjectRoot "release\Anonymisation-Setup.exe"

Require-Path -PathValue $InstallerScriptPath -Label "Script Inno Setup"
Require-Path -PathValue $PackageExePath -Label "Executable package"

$innoCompiler = Resolve-InnoCompiler
Write-Host "Inno Setup Compiler : $innoCompiler"
& $innoCompiler "/DAppVersion=$AppVersion" $InstallerScriptPath
if ($LASTEXITCODE -ne 0) {
    throw "Inno Setup a echoue avec le code $LASTEXITCODE."
}

Require-Path -PathValue $InstallerPath -Label "Installateur Windows"
$installerSizeMb = [math]::Round((Get-Item $InstallerPath).Length / 1MB, 1)
Write-Host "Installateur pret : $InstallerPath ($installerSizeMb MB)"
