param(
    [switch]$TagLatest
)

$ErrorActionPreference = 'Stop'
$ProjectRoot = Split-Path -Parent $PSScriptRoot
$Version = (Get-Content -LiteralPath (Join-Path $ProjectRoot 'VERSION') -Raw).Trim()

if ($Version -notmatch '^\d+\.\d+\.\d+([+-][0-9A-Za-z.-]+)?$') {
    throw "Version invalide dans VERSION: $Version"
}

$Revision = 'unknown'
if (Get-Command git -ErrorAction SilentlyContinue) {
    $candidate = git -C $ProjectRoot rev-parse --short HEAD 2>$null
    if ($LASTEXITCODE -eq 0 -and $candidate) {
        $Revision = $candidate.Trim()
    }
}

$env:GMAO_VERSION = $Version
$env:GIT_VERSION = $Revision

Push-Location $ProjectRoot
try {
    docker compose -f docker-compose.yml build gmao
    if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }

    if ($TagLatest) {
        if ($Version.Contains('-')) {
            throw 'Une preversion ne peut pas recevoir le tag latest.'
        }
        docker tag "gmao-college:$Version" 'gmao-college:latest'
        if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
    }
}
finally {
    Pop-Location
}

Write-Host "Image construite: gmao-college:$Version (revision $Revision)"
