param(
    [Parameter(Mandatory=$true)][string]$Registry,
    [Parameter(Mandatory=$true)][string]$Owner,
    [Parameter(Mandatory=$true)][string]$Repo,
    [string]$Tag = 'latest',
    [string]$Username = $null,
    [string]$Token = $null
)

if (-not $Registry -or -not $Owner -or -not $Repo) {
    Write-Error "Usage: .\scripts\build_and_push.ps1 -Registry <registry> -Owner <owner> -Repo <repo> [-Tag <tag>] [-Username <user>] [-Token <token>]"
    exit 1
}

$localImage = "$Repo:$Tag"
$remoteImage = "$Registry/$Owner/$Repo:$Tag"

Write-Host "Building image: $localImage"
docker build -t $localImage .

Write-Host "Tagging image -> $remoteImage"
docker tag $localImage $remoteImage

if ($Token) {
    Write-Host "Logging in to $Registry using token"
    $secureToken = ConvertTo-SecureString $Token -AsPlainText -Force
    $credential = New-Object System.Management.Automation.PSCredential($Username, $secureToken)
    $Token | docker login $Registry -u ${Username:-$Owner} --password-stdin
} else {
    Write-Host "Logging in to $Registry interactively"
    docker login $Registry -u ${Username:-$Owner}
}

Write-Host "Pushing $remoteImage"
docker push $remoteImage

Write-Host "Push finished: $remoteImage"
