name: Publish Python 🐍 distribution to PyPI on version bump

on:
  push:
    branches: [main]
    paths:
      - 'pyproject.toml'

jobs:
  publish:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: '3.13'

      - name: Install uv
        run: |
          pip install uv

      - name: Install dependencies
        run: |
          uv sync --no-dev

      - name: Get current version from pyproject.toml
        id: get_version
        run: |
          uv run python -c "import tomllib; print(tomllib.load(open('pyproject.toml', 'rb'))['project']['version'])" > version.txt
          echo "version=$(cat version.txt)" >> $GITHUB_OUTPUT

      - name: Get latest version from PyPI
        id: get_latest
        run: |
          PKG_NAME=$(uv run python -c "import tomllib; print(tomllib.load(open('pyproject.toml', 'rb'))['project']['name'])")
          LATEST_VERSION=$(curl -s https://pypi.org/pypi/$PKG_NAME/json | uv run python -c "import sys, json; data = json.load(sys.stdin); print(data['info']['version']) if 'info' in data else print('0.0.0')" 2>/dev/null || echo "0.0.0")
          echo "latest=$LATEST_VERSION" >> $GITHUB_OUTPUT

      - name: Compare versions and set publish flag
        id: check_version
        run: |
          SHOULD_PUBLISH=$(uv run python -c "
          from packaging.version import parse
          import os
          current = parse('${{ steps.get_version.outputs.version }}')
          latest = parse('${{ steps.get_latest.outputs.latest }}')
          print('true' if current > latest else 'false')
          ")
          echo "publish=$SHOULD_PUBLISH" >> $GITHUB_OUTPUT

      - name: Build package
        if: steps.check_version.outputs.publish == 'true'
        run: |
          uv build --sdist --wheel

      - name: Publish to PyPI
        if: steps.check_version.outputs.publish == 'true'
        env:
          PYPI_TOKEN: ${{ secrets.PYPI_TOKEN }}
        run: |
          uv publish --token $PYPI_TOKEN
