name: Publish to PyPI

on:
  push:
    branches: [ main ]
    paths:
      - "pyproject.toml"
      - "README.md"
      - "src/**"
      - "docs/source/**"
      - "Makefile"
      - "scripts/**"
  workflow_dispatch:

permissions:
  contents: read
  id-token: write

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

      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: "3.11"
          cache: "pip"

      - name: Install build tooling
        run: |
          python -m pip install -U pip
          python -m pip install build packaging

      - name: Read package version
        id: pkg
        run: |
          python - <<'PY'
          import os
          import tomllib
          from pathlib import Path

          data = tomllib.loads(Path("pyproject.toml").read_text())
          version = data["project"]["version"]
          print(f"Local version: {version}")

          with open(os.environ["GITHUB_OUTPUT"], "a", encoding="utf-8") as fh:
              fh.write(f"version={version}\n")
          PY

      - name: Compare against PyPI
        id: version_check
        env:
          LOCAL_VERSION: ${{ steps.pkg.outputs.version }}
        run: |
          python - <<'PY'
          import json
          import os
          import sys
          import urllib.request

          from packaging.version import Version

          package = "fermilink"
          local = os.environ["LOCAL_VERSION"]
          try:
              with urllib.request.urlopen(f"https://pypi.org/pypi/{package}/json") as resp:
                  data = json.load(resp)
                  published = data["info"]["version"]
          except Exception as exc:  # pragma: no cover - network guard
              print(f"Could not fetch PyPI metadata: {exc}")
              published = ""

          should_publish = not published or Version(local) > Version(published)
          print(f"PyPI version: {published or 'none'}")
          print(f"Publish? {should_publish}")

          with open(os.environ["GITHUB_OUTPUT"], "a", encoding="utf-8") as fh:
              fh.write(f"publish={'true' if should_publish else 'false'}\n")
              fh.write(f"pypi_version={published}\n")
          PY

      - name: Build distributions
        if: steps.version_check.outputs.publish == 'true'
        run: python -m build

      - name: Verify fermilink CLI from built wheel
        if: steps.version_check.outputs.publish == 'true'
        run: |
          set -euo pipefail
          python -m pip install --force-reinstall dist/*.whl
          python -m pip check
          fermilink --help
          python -m fermilink --help

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