name: Publish to PyPI

on:
  push:
    branches: [master]

jobs:
  publish:
    name: Build and publish
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          fetch-depth: 2

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

      - name: Detect version change
        id: version
        run: |
          NEW_VERSION=$(python - <<'PY'
import pathlib, tomllib
print(tomllib.loads(pathlib.Path('pyproject.toml').read_text())['project']['version'])
PY
)
          OLD_VERSION=$(git show HEAD^:pyproject.toml 2>/dev/null | python - <<'PY'
import sys, tomllib
print(tomllib.loads(sys.stdin.read())['project']['version'])
PY
 || echo '')
          echo "new=$NEW_VERSION" >> $GITHUB_OUTPUT
          echo "old=$OLD_VERSION" >> $GITHUB_OUTPUT
          if [ "$NEW_VERSION" != "$OLD_VERSION" ]; then
            echo "changed=true" >> $GITHUB_OUTPUT
          else
            echo "changed=false" >> $GITHUB_OUTPUT
          fi

      - name: Install build tools
        if: steps.version.outputs.changed == 'true'
        run: python -m pip install build

      - name: Build
        if: steps.version.outputs.changed == 'true'
        run: python -m build

      - name: Publish
        if: steps.version.outputs.changed == 'true'
        uses: pypa/gh-action-pypi-publish@release/v1
        with:
          password: ${{ secrets.PYPI_API_TOKEN }}

