# mosaic-release-upgrade.ps1 — Upgrade installed Mosaic framework release (Windows)
#
# Usage:
#   mosaic-release-upgrade.ps1
#   mosaic-release-upgrade.ps1 -Ref main -Keep
#   mosaic-release-upgrade.ps1 -Ref v0.2.0 -Overwrite -Yes
#
param(
    [string]$Ref = $(if ($env:MOSAIC_BOOTSTRAP_REF) { $env:MOSAIC_BOOTSTRAP_REF } else { "main" }),
    [switch]$Keep,
    [switch]$Overwrite,
    [switch]$Yes,
    [switch]$DryRun
)

$ErrorActionPreference = "Stop"

$MosaicHome = if ($env:MOSAIC_HOME) { $env:MOSAIC_HOME } else { Join-Path $env:USERPROFILE ".config\mosaic" }
$RemoteInstallerUrl = if ($env:MOSAIC_REMOTE_INSTALL_URL) {
    $env:MOSAIC_REMOTE_INSTALL_URL
} else {
    "https://git.mosaicstack.dev/mosaic/mosaic-stack/raw/branch/main/tools/install.sh"
}

$installMode = if ($Overwrite) { "overwrite" } elseif ($Keep) { "keep" } elseif ($env:MOSAIC_INSTALL_MODE) { $env:MOSAIC_INSTALL_MODE } else { "keep" }
if ($installMode -notin @("keep", "overwrite")) {
    Write-Host "[mosaic-release-upgrade] Invalid install mode: $installMode" -ForegroundColor Red
    exit 1
}

$currentVersion = "unknown"
$mosaicCmd = Join-Path $MosaicHome "bin\mosaic.ps1"
if (Test-Path $mosaicCmd) {
    try {
        $currentVersion = (& $mosaicCmd --version) -replace '^mosaic\s+', ''
    }
    catch {
        $currentVersion = "unknown"
    }
}

Write-Host "[mosaic-release-upgrade] Current version: $currentVersion"
Write-Host "[mosaic-release-upgrade] Target ref: $Ref"
Write-Host "[mosaic-release-upgrade] Install mode: $installMode"
Write-Host "[mosaic-release-upgrade] Installer URL: $RemoteInstallerUrl"

if ($DryRun) {
    Write-Host "[mosaic-release-upgrade] Dry run: no changes applied."
    exit 0
}

if (-not $Yes) {
    $confirmation = Read-Host "Proceed with Mosaic release upgrade? [y/N]"
    if ($confirmation -notin @("y", "Y", "yes", "YES")) {
        Write-Host "[mosaic-release-upgrade] Aborted."
        exit 1
    }
}

$env:MOSAIC_BOOTSTRAP_REF = $Ref
$env:MOSAIC_INSTALL_MODE = $installMode
$env:MOSAIC_HOME = $MosaicHome

Invoke-RestMethod -Uri $RemoteInstallerUrl | Invoke-Expression

