$ErrorActionPreference = 'Stop'

function Ensure-Success($exitCode, $what) {
    if ($exitCode -ne 0) {
        throw "Failed: $what (exit code $exitCode)"
    }
}

function Get-VersionFromUser {
    $version = Read-Host "Enter version (e.g. 1.2.3)"
    $version = $version.Trim()
    if ([string]::IsNullOrWhiteSpace($version)) {
        throw "Version cannot be empty"
    }
    # Basic docker tag safety: allow only common characters
    if ($version -notmatch '^[0-9A-Za-z][0-9A-Za-z._-]{0,127}$') {
        throw "Invalid version '$version'. Use only letters/numbers and . _ - (max 128 chars)"
    }
    return $version
}

$TargetGitUrl = "https://git.alphen.cloud/bramval/PsalmbordOnlineCE.git"
$DockerImage  = "git.alphen.cloud/bramval/psalmbordonlinece"

$gitCmd = Get-Command git -ErrorAction SilentlyContinue
if (-not $gitCmd) { throw "git is not available in PATH" }
$dockerCmd = Get-Command docker -ErrorAction SilentlyContinue
if (-not $dockerCmd) { throw "docker is not available in PATH" }

$version = Get-VersionFromUser
$commitMessage = "Version $version"

$branch = (git branch --show-current).Trim()
if ($branch -ne 'main') {
    Write-Host "You are on branch '$branch' (expected 'main')." -ForegroundColor Yellow
    $ans = Read-Host "Continue and push 'main' anyway? (y/N)"
    if ($ans.ToLower() -ne 'y') { throw "Aborted by user" }
}

Write-Host "\n== Git: ensuring remote 'origin' points to $TargetGitUrl ==" -ForegroundColor Cyan
$originUrl = (git remote get-url origin 2>$null)
if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($originUrl)) {
    Write-Host "Remote 'origin' not found; adding it." -ForegroundColor Yellow
    git remote add origin $TargetGitUrl
    Ensure-Success $LASTEXITCODE "git remote add"
} elseif ($originUrl -ne $TargetGitUrl) {
    Write-Host "Remote 'origin' is '$originUrl' -> updating to '$TargetGitUrl'" -ForegroundColor Yellow
    git remote set-url origin $TargetGitUrl
    Ensure-Success $LASTEXITCODE "git remote set-url"
}

Write-Host "\n== Git: status ==" -ForegroundColor Cyan
git status -sb

$confirm = Read-Host "Proceed with commit+push and docker push? (y/N)"
if ($confirm.ToLower() -ne 'y') { throw "Aborted by user" }

Write-Host "\n== Git: add/commit/push ==" -ForegroundColor Cyan
git add -A
Ensure-Success $LASTEXITCODE "git add"

# Commit might fail if nothing to commit; handle gracefully
git commit -m $commitMessage
if ($LASTEXITCODE -ne 0) {
    Write-Host "No changes to commit (or commit failed). Continuing to push anyway..." -ForegroundColor Yellow
} else {
    Write-Host "Committed: $commitMessage" -ForegroundColor Green
}

git push -u origin main
Ensure-Success $LASTEXITCODE "git push"

Write-Host "\n== Docker: build/tag/push ==" -ForegroundColor Cyan
Write-Host "Docker image: $DockerImage" -ForegroundColor Gray
Write-Host "Tags: $version, latest" -ForegroundColor Gray

docker build -t "${DockerImage}:${version}" -t "${DockerImage}:latest" .
Ensure-Success $LASTEXITCODE "docker build"

docker push "${DockerImage}:${version}"
Ensure-Success $LASTEXITCODE "docker push (version)"

docker push "${DockerImage}:latest"
Ensure-Success $LASTEXITCODE "docker push (latest)"

Write-Host "\nDone." -ForegroundColor Green
Write-Host "If docker push failed due to auth, run: docker login git.alphen.cloud" -ForegroundColor Yellow
