#!/bin/sh
# scripts/publish-wheel — build, verify, and (optionally) publish the
# mgf-hrb Python SDK wheel FROM THIS MONOREPO.
#
# WHY here and not a separate repo: the broker (hrb-code/) and the SDK
# (src/mgf/hrb/) share one repo on purpose — the line-JSON wire protocol
# is their contract, and keeping them in lockstep prevents version skew
# (see README "lockstep"). Consumers still get a normal `pip install`-able
# wheel; it is just published FROM the monorepo rather than carved out.
#
# The wheel is SDK-only (packages = ["src/mgf"]); tests and hrb-code/ are
# excluded, asserted by scripts/verify_wheel_contents.sh.
#
# Usage:
#   scripts/publish-wheel              # build + verify (dry run; no upload)
#   scripts/publish-wheel --upload     # also upload to the index
#
# Upload target + auth (only read when --upload is given):
#   $PUBLISH_URL   index URL (default: PyPI). For Codeberg's registry use
#                  https://codeberg.org/api/packages/magogi-admin/pypi
#   $PYPI_TOKEN    token; else my_stuff/ssh_key/pypi_token.txt (gitignored)
# The token is never written to a committed file.
#
# Exit codes: 0 ok; 1 build/verify/upload failure; 2 usage error.
set -eu

REPO_ROOT="$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)"
cd "$REPO_ROOT"

upload=0
for arg in "$@"; do
    case "$arg" in
        --upload) upload=1 ;;
        -h|--help) sed -n '1,/^set/p' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;;
        *) printf 'publish-wheel: unknown flag: %s\n' "$arg" >&2; exit 2 ;;
    esac
done

printf '== building wheel ==\n'
rm -rf dist
uv build --wheel

printf '== verifying wheel contents ==\n'
scripts/verify_wheel_contents.sh

if [ "$upload" -eq 0 ]; then
    printf '\nDry run complete (built + verified). Pass --upload to publish.\n'
    exit 0
fi

TOKEN="${PYPI_TOKEN:-}"
if [ -z "$TOKEN" ] && [ -f "$REPO_ROOT/my_stuff/ssh_key/pypi_token.txt" ]; then
    TOKEN="$(tr -d '\n' < "$REPO_ROOT/my_stuff/ssh_key/pypi_token.txt")"
fi
if [ -z "$TOKEN" ]; then
    printf 'publish-wheel: no token (set PYPI_TOKEN or my_stuff/ssh_key/pypi_token.txt)\n' >&2
    exit 1
fi

printf '== uploading ==\n'
if [ -n "${PUBLISH_URL:-}" ]; then
    uv publish --publish-url "$PUBLISH_URL" --token "$TOKEN" dist/*.whl
else
    uv publish --token "$TOKEN" dist/*.whl
fi
printf 'published.\n'
