name: Build and publish to PyPI

on:
  release:
    types: [published]
  workflow_dispatch:

jobs:
  build:
    name: Build distributions
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

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

      - name: Install build tools
        run: python -m pip install --upgrade pip build twine

      - name: Install project dependencies
        run: python -m pip install .

      - name: Read package version
        id: version
        run: |
          python - <<'PY'
          import os
          import pathlib
          import tomllib
          version = tomllib.loads(pathlib.Path("pyproject.toml").read_text())["project"][
              "version"
          ]
          print(version)
          with open(os.environ["GITHUB_OUTPUT"], "a", encoding="utf-8") as f:
              f.write(f"version={version}\n")
          PY

      - name: Validate release tag matches version
        if: github.event_name == 'release'
        env:
          TAG_NAME: ${{ github.event.release.tag_name }}
        run: |
          python - <<'PY'
          import os
          tag = os.environ["TAG_NAME"]
          if tag.startswith("v"):
            tag = tag[1:]
          # `steps.version.outputs.version` is available via GHA expressions only, so re-read here.
          import pathlib, tomllib
          version = tomllib.loads(pathlib.Path("pyproject.toml").read_text())["project"]["version"]
          if tag != version:
            raise SystemExit(f"Release tag ({tag}) does not match pyproject.toml version ({version})")
          print("Tag matches version:", tag)
          PY

      - name: Build sdist and wheel
        run: python -m build --sdist --wheel --outdir dist/

      - name: Python compile check
        run: python -m py_compile tpcav/*.py scripts/*.py test/*.py

      - name: Twine check
        run: python -m twine check --strict dist/*

      - uses: actions/upload-artifact@v4
        with:
          name: dist
          path: dist/

  publish:
    name: Publish to PyPI
    needs: build
    runs-on: ubuntu-latest
    if: github.event_name == 'release'
    environment:
      name: pypi
      url: https://pypi.org/project/tpcav/
    permissions:
      id-token: write
      contents: read
    steps:
      - uses: actions/download-artifact@v4
        with:
          name: dist
          path: dist/

      - name: Publish
        uses: pypa/gh-action-pypi-publish@release/v1
        with:
          packages-dir: dist/
