$ErrorActionPreference = 'Stop'
# Usage: .\scripts\bump-version.ps1 <semver|patch|minor|major>

# ---------------------------------------------------------------------------
# T-02: Validação de argumento
# ---------------------------------------------------------------------------
if ($args.Count -ne 1) {
    [Console]::Error.WriteLine("Uso: .\scripts\bump-version.ps1 <patch|minor|major|X.Y.Z>")
    exit 2
}

$Arg = $args[0]

# Aceitar: patch, minor, major, ou semver X.Y.Z (apenas dígitos e pontos)
if ($Arg -eq 'patch' -or $Arg -eq 'minor' -or $Arg -eq 'major') {
    # válido
} elseif ($Arg -match '^\d+\.\d+\.\d+$') {
    # semver explícito — válido
} else {
    [Console]::Error.WriteLine("Erro: argumento inválido '$Arg'. Use patch, minor, major ou X.Y.Z.")
    exit 2
}

# ---------------------------------------------------------------------------
# T-03: Resolução de versão alvo
# ---------------------------------------------------------------------------
$Current = (Get-Content VERSION -Raw).Trim()

if ($Current -notmatch '^\d+\.\d+\.\d+$') {
    [Console]::Error.WriteLine("Erro: VERSION contém valor inválido ('$Current'). Esperado X.Y.Z.")
    exit 1
}

$parts = $Current.Split('.')
[int]$Major = $parts[0]
[int]$Minor = $parts[1]
[int]$Patch = $parts[2]

switch ($Arg) {
    'patch' {
        $Patch = $Patch + 1
        $Target = "$Major.$Minor.$Patch"
    }
    'minor' {
        $Minor = $Minor + 1
        $Patch = 0
        $Target = "$Major.$Minor.$Patch"
    }
    'major' {
        $Major = $Major + 1
        $Minor = 0
        $Patch = 0
        $Target = "$Major.$Minor.$Patch"
    }
    default {
        $Target = $Arg
    }
}

# ---------------------------------------------------------------------------
# T-04: Backup + edição cirúrgica de Cargo.toml (máquina de estado por seção)
# ---------------------------------------------------------------------------
Copy-Item Cargo.toml Cargo.toml.bak
Copy-Item Cargo.lock Cargo.lock.bak

$lines = Get-Content Cargo.toml
$inPkg = $false
$done = $false
$result = foreach ($line in $lines) {
    if ($line -match '^\[') { $inPkg = ($line -eq '[package]') }
    if ($inPkg -and ($line.TrimStart() -match '^version\s*=') -and -not $done) {
        "version = `"$Target`""
        $done = $true
    } else {
        $line
    }
}
$result | Set-Content Cargo.toml

# ---------------------------------------------------------------------------
# T-05: cargo update + escrita de VERSION + rollback em falha
# ---------------------------------------------------------------------------
cargo update -p sdd-layer --precise $Target
if ($LASTEXITCODE -ne 0) {
    Copy-Item Cargo.toml.bak Cargo.toml -Force
    Copy-Item Cargo.lock.bak Cargo.lock -Force
    Remove-Item Cargo.toml.bak, Cargo.lock.bak -Force -ErrorAction SilentlyContinue
    [Console]::Error.WriteLine("Erro: cargo update -p sdd-layer --precise $Target falhou. Rollback executado.")
    exit 1
}

Set-Content VERSION $Target -NoNewline
Add-Content VERSION ""

Remove-Item Cargo.toml.bak, Cargo.lock.bak -Force

# ---------------------------------------------------------------------------
# T-06: Saída resumo + exit 0
# ---------------------------------------------------------------------------
Write-Host "bump-version: $Current -> $Target"
Write-Host "  VERSION      $Target"
Write-Host "  Cargo.toml   $Target"
Write-Host "  Cargo.lock   $Target  (sdd-layer)"
Write-Host "OK"
exit 0
