param(
  [Parameter(Mandatory=$false)]
  [string]$Version
)

$ErrorActionPreference = 'Stop'

function Invoke-Checked {
  param(
    [Parameter(Mandatory=$true)]
    [scriptblock]$Command,
    [Parameter(Mandatory=$true)]
    [string]$What
  )

  & $Command
  if ($LASTEXITCODE -ne 0) {
    throw "Failed: $What (exit code $LASTEXITCODE)"
  }
}

Push-Location $PSScriptRoot

try {
  if ($Version -and $Version.Trim().Length -gt 0) {
    Write-Host "NOTE: This script does not bump version automatically." -ForegroundColor Yellow
    Write-Host "Set version to $Version in pyproject.toml before publishing." -ForegroundColor Yellow
  }

  Invoke-Checked { python -m pip install -U pip } "pip upgrade"
  Invoke-Checked { python -m pip install -U build twine } "install build tooling"

  if (Test-Path dist) {
    Remove-Item -Recurse -Force dist
  }

  Invoke-Checked { python -m build } "build dist"
  Invoke-Checked { python -m twine check dist/* } "twine check"

  Write-Host "Uploading to TestPyPI..." -ForegroundColor Cyan
  Write-Host "When prompted: username=__token__ password=<your TestPyPI token>" -ForegroundColor Cyan
  Invoke-Checked { python -m twine upload --repository-url https://test.pypi.org/legacy/ dist/* } "twine upload"
}
finally {
  Pop-Location
}
