$ErrorActionPreference = "Stop"

# Basic configuration
$ScriptPath = $PSScriptRoot
$ProjectFile = (Get-ChildItem -Path $ScriptPath -Filter "*.csproj" -File)[0].FullName
$SetupScript = Join-Path $ScriptPath "setup.iss"

# Read version from project file
$currentVersion = "1.0.0"
[xml]$csproj = Get-Content $ProjectFile
if ($csproj.Project.PropertyGroup.Version) {
    $currentVersion = $csproj.Project.PropertyGroup.Version
}

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

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

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

# Build project
dotnet publish $ProjectFile -c Release -r win-x64 --self-contained false -p:PublishSingleFile=true
if ($LASTEXITCODE -ne 0) {
    Write-Error "Build failed"
    exit 1
}

# Package
$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"
}
