param(
    [switch]$Clean,
    [switch]$SkipGhostscriptBundle
)

$ErrorActionPreference = "Stop"

$ProjectRoot = Split-Path -Parent $MyInvocation.MyCommand.Path
Set-Location $ProjectRoot

$AppName = "ZipBundler"
$EntryPoint = Join-Path $ProjectRoot "zipbundler.py"
$SplashImage = Join-Path $ProjectRoot "assets\splash.png"

if (-not (Test-Path -LiteralPath $EntryPoint)) {
    throw "File principale non trovato: $EntryPoint"
}

if (-not (Test-Path -LiteralPath $SplashImage)) {
    throw "Immagine splash non trovata: $SplashImage"
}

if ($Clean) {
    Remove-Item -LiteralPath (Join-Path $ProjectRoot "build") -Recurse -Force -ErrorAction SilentlyContinue
    Remove-Item -LiteralPath (Join-Path $ProjectRoot "dist") -Recurse -Force -ErrorAction SilentlyContinue
    Remove-Item -LiteralPath (Join-Path $ProjectRoot "$AppName.spec") -Force -ErrorAction SilentlyContinue
}

python -m pip install --upgrade pip
python -m pip install -r requirements.txt
python -m pip install --upgrade pyinstaller

$argsList = @(
    "--noconfirm",
    "--clean",
    "--windowed",
    "--onefile",
    "--name", $AppName,
    "--splash", $SplashImage,
    "--add-data", "$SplashImage;assets",
    "--hidden-import", "customtkinter",
    "--hidden-import", "PIL._tkinter_finder",
    "--hidden-import", "fitz",
    "--hidden-import", "win32com",
    "--hidden-import", "win32com.client",
    "--hidden-import", "pythoncom"
)

if (-not $SkipGhostscriptBundle) {
    $ghostscriptCommand = Get-Command gswin64c.exe, gswin32c.exe, gs.exe -ErrorAction SilentlyContinue | Select-Object -First 1
    if ($ghostscriptCommand) {
        $ghostscriptBin = Split-Path -Parent $ghostscriptCommand.Source
        $ghostscriptRoot = Split-Path -Parent $ghostscriptBin
        Write-Host "Includo Ghostscript da: $ghostscriptRoot"
        $argsList += @("--add-data", "$ghostscriptRoot;ghostscript")
    }
    else {
        Write-Warning "Ghostscript non trovato nel PATH. Il programma usera Ghostscript solo se installato sul PC di destinazione."
    }
}
else {
    Write-Warning "Bundle Ghostscript saltato per richiesta esplicita."
}

$argsList += $EntryPoint

python -m PyInstaller @argsList

$exePath = Join-Path $ProjectRoot "dist\$AppName.exe"
if (Test-Path -LiteralPath $exePath) {
    Write-Host ""
    Write-Host "Build completata:"
    Write-Host $exePath
}
else {
    throw "Build completata senza trovare l'eseguibile atteso: $exePath"
}
