name: Publish to PyPI

on:
  release:
    types: [published]

jobs:
  publish:
    runs-on: ubuntu-latest
    environment: pypi
    permissions:
      id-token: write  # Required for trusted publishing

    steps:
      - uses: actions/checkout@v4

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

      - name: Install build tools
        run: pip install build

      - name: Validate release version
        env:
          GITHUB_REF_NAME: ${{ github.ref_name }}
        run: |
          python scripts/sync_versions.py
          python - <<'PY'
          import os
          import pathlib
          import tomllib

          tag = os.environ.get("GITHUB_REF_NAME", "")
          if tag.startswith("refs/tags/"):
              tag = tag.split("/", 2)[-1]
          if tag.startswith("v"):
              tag = tag[1:]

          pyproject = tomllib.loads(pathlib.Path("pyproject.toml").read_text())["project"]["version"]

          errors = []
          if tag and tag != pyproject:
              errors.append(f"Release tag v{tag} does not match pyproject version {pyproject}")

          if errors:
              raise SystemExit("\n".join(errors))
          print(f"Version ok: {pyproject}")
          PY

      - name: Build package
        run: python -m build

      - name: Publish to PyPI
        uses: pypa/gh-action-pypi-publish@release/v1
