param(
    [string]$DownloadUrl = "https://jrsoftware.org/download.php/is.exe"
)

$ErrorActionPreference = "Stop"

function Write-Step {
    param([string]$Message)
    Write-Host ""
    Write-Host "=== $Message ===" -ForegroundColor Cyan
}

function Find-InnoCompiler {
    $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
        }
    }
    return $null
}

$existing = Find-InnoCompiler
if ($existing) {
    Write-Host "Inno Setup deja disponible : $existing"
    exit 0
}

Write-Step "Telechargement Inno Setup"
$installerPath = Join-Path $env:TEMP "innosetup-build-dep.exe"
Invoke-WebRequest -Uri $DownloadUrl -OutFile $installerPath
Write-Host "Installeur telecharge : $installerPath"

Write-Step "Installation Inno Setup utilisateur"
$args = @("/SP-", "/VERYSILENT", "/SUPPRESSMSGBOXES", "/NORESTART", "/CURRENTUSER")
$process = Start-Process -FilePath $installerPath -ArgumentList $args -Wait -PassThru
Write-Host "Code retour : $($process.ExitCode)"
if ($process.ExitCode -ne 0) {
    throw "Installation Inno Setup echouee avec le code $($process.ExitCode)."
}

$compiler = Find-InnoCompiler
if (-not $compiler) {
    throw "ISCC.exe introuvable apres installation Inno Setup."
}

Write-Host "Inno Setup pret : $compiler"
