$ErrorActionPreference = "Stop"

$ScriptPath = $PSScriptRoot
$ProjectDir = Join-Path $ScriptPath "src\TodoList.Maui"
$ProjectFile = Join-Path $ProjectDir "TodoList.Maui.csproj"
$SetupScript = Join-Path $ProjectDir "setup.iss"

# Read version from project file
$currentVersion = "1.0.0"
[xml]$csproj = Get-Content $ProjectFile -Raw
$versionNode = $csproj.SelectSingleNode("//Version")
if ($null -ne $versionNode) {
    $currentVersion = $versionNode.InnerText
} else {
    $versionNode = $csproj.SelectSingleNode("//ApplicationDisplayVersion")
    if ($null -ne $versionNode) {
        $currentVersion = $versionNode.InnerText
    }
}

# Update setup script version with current version before build
if (Test-Path $SetupScript) {
    $issContent = Get-Content $SetupScript
    $versionFound = $false
    for ($i = 0; $i -lt $issContent.Count; $i++) {
        if ($issContent[$i] -like '#define MyAppVersion *') {
            $issContent[$i] = '#define MyAppVersion "' + $currentVersion + '"'
            $versionFound = $true
            break
        }
    }
    if ($versionFound) {
        Set-Content $SetupScript -Value $issContent
    }
}

Write-Host "Building TodoList.Maui (Release)..." -ForegroundColor Cyan
dotnet publish $ProjectFile -f net10.0-windows10.0.19041.0 -c Release --self-contained false
if ($LASTEXITCODE -ne 0) {
    Write-Error "MAUI build failed"
    exit 1
}

$ISCC = "${env:ProgramFiles(x86)}\Inno Setup 6\ISCC.exe"
if (Test-Path $ISCC) {
    & $ISCC $SetupScript
    if ($LASTEXITCODE -eq 0) {
        Write-Host "Setup package created successfully!" -ForegroundColor Green
    } else {
        Write-Error "Packaging failed"
    }
} else {
    Write-Error "Inno Setup compiler not found"
}

$versionParts = $currentVersion.Split(".")
$patch = [int]$versionParts[2] + 1
$newVersion = $versionParts[0] + "." + $versionParts[1] + "." + $patch

$content = Get-Content $ProjectFile -Raw
$content = $content -replace "<Version>.*</Version>", "<Version>$newVersion</Version>"
Set-Content $ProjectFile -Value $content
