#!/bin/bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "$0")" && pwd)"
cd "$ROOT_DIR"

if [ ! -f "pyproject.toml" ]; then
    echo "Error: run from packages/agent-sdk/python"
    exit 1
fi

VERSION="$(python3 - <<'PY'
from pathlib import Path
import re

text = Path("pyproject.toml").read_text()
match = re.search(r'^version = "([^"]+)"$', text, re.MULTILINE)
if not match:
    raise SystemExit("Unable to determine version from pyproject.toml")
print(match.group(1))
PY
)"

echo "======================================================================"
echo "Publishing paegents v${VERSION} to PyPI"
echo "======================================================================"
echo ""

if [ ! -d "dist" ]; then
    echo "Error: dist/ not found. Run 'python3 -m build' first."
    exit 1
fi

echo "Package files ready:"
ls -lh dist/
echo ""

echo "Validating packages..."
python3 -m twine check dist/*
echo "Packages validated"
echo ""

echo "Choose authentication method:"
echo "  1) Username & Password (interactive)"
echo "  2) API Token (interactive)"
echo "  3) Cancel"
read -r -p "Enter choice (1-3): " choice

case "$choice" in
    1)
        python3 -m twine upload dist/*
        ;;
    2)
        read -r -p "Enter your PyPI API token: " token
        if [ -z "$token" ]; then
            echo "Error: no token provided"
            exit 1
        fi
        python3 -m twine upload -u __token__ -p "$token" dist/*
        ;;
    3)
        echo "Cancelled"
        exit 0
        ;;
    *)
        echo "Error: invalid choice"
        exit 1
        ;;
esac

echo ""
echo "Published paegents v${VERSION}"
echo "https://pypi.org/project/paegents/${VERSION}/"
