# Build Jellyfin Installer
# This script builds the Jellyfin installer using Inno Setup

param(
    [Parameter(Mandatory=$false)]
    [string]$Version = "11.0.0-PostgreSQL-PREVIEW",

    [Parameter(Mandatory=$false)]
    [ValidateSet("Release", "Debug")]
    [string]$Configuration = "Release",

    [Parameter(Mandatory=$false)]
    [switch]$SkipBuild
)

Write-Host "`n╔══════════════════════════════════════════════════════════╗" -ForegroundColor Cyan
Write-Host "║       Jellyfin PostgreSQL Installer Builder             ║" -ForegroundColor Cyan
Write-Host "╚══════════════════════════════════════════════════════════╝`n" -ForegroundColor Cyan

$ErrorActionPreference = "Stop"
$ScriptDir = $PSScriptRoot
$SolutionRoot = "E:\Projects\pgsql-jellyfin"
$InnoSetupPath = "${env:ProgramFiles(x86)}\Inno Setup 6\ISCC.exe"

# Check prerequisites
Write-Host "Checking prerequisites..." -ForegroundColor Yellow

# Check if Inno Setup is installed
if (-not (Test-Path $InnoSetupPath)) {
    Write-Host "❌ Inno Setup 6 not found!" -ForegroundColor Red
    Write-Host "Please install it from: https://jrsoftware.org/isinfo.php" -ForegroundColor Yellow
    Write-Host "Or run: winget install JRSoftware.InnoSetup" -ForegroundColor Yellow
    exit 1
}
Write-Host "✅ Inno Setup found" -ForegroundColor Green

# Check if lib folder exists
if (-not (Test-Path "$SolutionRoot\lib\$Configuration\net11.0")) {
    if ($SkipBuild) {
        Write-Host "❌ Build folder not found: $SolutionRoot\lib\$Configuration\net11.0" -ForegroundColor Red
        exit 1
    }
    Write-Host "⚠️  Build folder not found, building solution first..." -ForegroundColor Yellow
}

# Build the solution if needed
if (-not $SkipBuild) {
    Write-Host "`nBuilding Jellyfin solution..." -ForegroundColor Cyan
    Push-Location $SolutionRoot

    try {
        # Clean previous build
        Write-Host "Cleaning previous build..." -ForegroundColor Gray
        dotnet clean --configuration $Configuration | Out-Null

        # Build solution
        Write-Host "Building $Configuration configuration..." -ForegroundColor Gray
        $buildOutput = dotnet build Jellyfin.Server --configuration $Configuration 2>&1

        if ($LASTEXITCODE -ne 0) {
            Write-Host "❌ Build failed!" -ForegroundColor Red
            Write-Host $buildOutput
            exit 1
        }

        Write-Host "✅ Build successful" -ForegroundColor Green

        # Count DLLs
        $dllCount = (Get-ChildItem "$SolutionRoot\lib\$Configuration\net11.0" -Filter "*.dll" -Recurse).Count
        Write-Host "📊 Built $dllCount DLL files" -ForegroundColor Gray
    }
    finally {
        Pop-Location
    }
}

# Check if installer script exists
$InnoScriptPath = "$SolutionRoot\jellyfin-setup.iss"
if (-not (Test-Path $InnoScriptPath)) {
    Write-Host "❌ Installer script not found: $InnoScriptPath" -ForegroundColor Red
    Write-Host "Please ensure jellyfin-setup.iss is in the solution root" -ForegroundColor Yellow
    exit 1
}

# Check for icon file (optional)
$IconPath = "$SolutionRoot\jellyfin.ico"
if (-not (Test-Path $IconPath)) {
    Write-Host "⚠️  Icon file not found: $IconPath" -ForegroundColor Yellow
    Write-Host "The installer will use the default Inno Setup icon" -ForegroundColor Gray
}

# Update version in script if needed
Write-Host "`nPreparing installer script..." -ForegroundColor Cyan
$scriptContent = Get-Content $InnoScriptPath -Raw
$scriptContent = $scriptContent -replace 'AppVersion=[\d\.]+', "AppVersion=$Version"
$scriptContent = $scriptContent -replace 'OutputBaseFilename=JellyfinSetup-PostgreSQL-[\d\.]+', "OutputBaseFilename=JellyfinSetup-PostgreSQL-$Version"
Set-Content $InnoScriptPath $scriptContent -NoNewline
Write-Host "✅ Version updated to $Version" -ForegroundColor Green

# Create output directory
$OutputDir = "$SolutionRoot\installer-output"
New-Item -ItemType Directory -Path $OutputDir -Force | Out-Null

# Build the installer
Write-Host "`nBuilding installer..." -ForegroundColor Cyan
Write-Host "Script: $InnoScriptPath" -ForegroundColor Gray
Write-Host "Output: $OutputDir" -ForegroundColor Gray

Push-Location $SolutionRoot

try {
    $compileOutput = & $InnoSetupPath $InnoScriptPath 2>&1
    
    if ($LASTEXITCODE -ne 0) {
        Write-Host "❌ Installer build failed!" -ForegroundColor Red
        Write-Host $compileOutput
        exit 1
    }
    
    Write-Host "✅ Installer built successfully!" -ForegroundColor Green
}
finally {
    Pop-Location
}

# Find the installer file
$installerFile = Get-ChildItem $OutputDir -Filter "JellyfinSetup-PostgreSQL-*.exe" | Sort-Object LastWriteTime -Descending | Select-Object -First 1

if ($installerFile) {
    $fileSize = [math]::Round($installerFile.Length / 1MB, 2)
    
    Write-Host "`n╔══════════════════════════════════════════════════════════╗" -ForegroundColor Green
    Write-Host "║              Installer Build Complete! ✅                ║" -ForegroundColor Green
    Write-Host "╚══════════════════════════════════════════════════════════╝`n" -ForegroundColor Green
    
    Write-Host "📦 Installer Details:" -ForegroundColor Cyan
    Write-Host "   File: $($installerFile.Name)" -ForegroundColor White
    Write-Host "   Path: $($installerFile.FullName)" -ForegroundColor White
    Write-Host "   Size: $fileSize MB" -ForegroundColor White
    Write-Host "   Date: $($installerFile.LastWriteTime)" -ForegroundColor White
    
    Write-Host "`n📋 Next Steps:" -ForegroundColor Cyan
    Write-Host "   1. Test the installer on a clean Windows system" -ForegroundColor Gray
    Write-Host "   2. Sign the installer (optional): signtool sign /f cert.pfx installer.exe" -ForegroundColor Gray
    Write-Host "   3. Upload to GitHub releases or your distribution server" -ForegroundColor Gray
    
    Write-Host "`n🧪 Test Commands:" -ForegroundColor Cyan
    Write-Host "   # Silent install" -ForegroundColor Gray
    Write-Host "   $($installerFile.FullName) /VERYSILENT /LOG=install.log" -ForegroundColor DarkGray
    Write-Host "   # Normal install" -ForegroundColor Gray
    Write-Host "   $($installerFile.FullName)" -ForegroundColor DarkGray
    
    # Open output folder
    Write-Host "`nOpening output folder..." -ForegroundColor Cyan
    Start-Process $OutputDir
}
else {
    Write-Host "❌ Installer file not found in output directory!" -ForegroundColor Red
    exit 1
}

Write-Host "`n✅ All done!`n" -ForegroundColor Green
