function Bump-Build {
param (
    [string]$AppRoot,
    [int]$KeepLast = 5   # number of builds to keep, default 5
)

$BuildFile = Join-Path $AppRoot ".controller-build"
$BuildFolder = Join-Path $AppRoot "controllerBuilds"

# Default to 1
$BuildNumber = 1


if (Test-Path $BuildFile) {
    $content = Get-Content $BuildFile | Select-Object -First 1
    $num = $content.Trim() -as [int]  # safe cast

    if ($num) {
        $BuildNumber = $num + 1
    } else {
        $BuildNumber = 1
    }
}

# Convert to string
$BuildNumber = $BuildNumber.ToString()

# Save new build number
Set-Content -Path $BuildFile -Value $BuildNumber

Write-Output "New Build Number: $BuildNumber"

# --- Cleanup old builds ---
if (Test-Path $BuildFolder) {
    # Get all zip files in build folder matching pattern
    $zips = Get-ChildItem -Path $BuildFolder -Filter "controllers-*.zip" | 
            Sort-Object LastWriteTime -Descending

    # Keep only the newest $KeepLast, remove the rest
    if ($zips.Count -gt $KeepLast) {
        $toRemove = $zips[$KeepLast..($zips.Count - 1)]
        foreach ($zip in $toRemove) {
            Remove-Item $zip.FullName -Force
            Write-Output "Removed old build: $($zip.Name)"
        }
    }
}

}