# scripts/docker_push.ps1
# Build and push Manual Slop image to Gitea container registry.

$ErrorActionPreference = "Stop"

$ProjectRoot = Split-Path -Parent $PSScriptRoot
$CredsFile = Join-Path $ProjectRoot "credentials.toml"

if (-not (Test-Path $CredsFile)) {
    Write-Error "credentials.toml not found at $CredsFile"
    exit 1
}

Write-Host "Reading credentials from credentials.toml..."

$pyScript = @"
import tomllib
with open(r'$CredsFile', 'rb') as f:
    creds = tomllib.load(f)
g = creds.get('gitea', {})
print(g.get('registry_url', '') + '|' + g.get('username', '') + '|' + g.get('token', ''))
"@

$credsJson = python -c $pyScript

$parts = $credsJson -split '\|'
$registryUrl = $parts[0].TrimEnd('/')
$giteaUser = $parts[1]
$giteaToken = $parts[2]

if (-not $registryUrl -or -not $giteaUser -or -not $giteaToken) {
    Write-Error "Gitea credentials incomplete in credentials.toml"
    Write-Error "Required: registry_url, username, token"
    exit 1
}

$registryHost = $registryUrl -replace 'https?://', ''
$imageName = "manual_slop:latest"
$fullTag = "$registryHost/$giteaUser/$imageName"

Write-Host "Building Docker image..."
docker build -t $imageName $ProjectRoot

Write-Host "Tagging for Gitea registry: $fullTag"
docker tag $imageName $fullTag

Write-Host "Logging in to Gitea registry..."
$giteaToken | docker login $registryHost -u $giteaUser --password-stdin

Write-Host "Pushing to Gitea registry..."
docker push $fullTag

Write-Host "Done! Image available at: $fullTag"