name: Publish to PyPI

on:
  workflow_run:
    workflows: ["CI"]
    types: [completed]

concurrency:
  group: publish-${{ github.event.workflow_run.head_sha }}
  cancel-in-progress: true

permissions:
  contents: write
  id-token: write

jobs:
  publish:
    if: github.event.workflow_run.conclusion == 'success'
    runs-on: ubuntu-latest
    environment: pypi
    steps:
      - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
        with:
          ref: ${{ github.event.workflow_run.head_sha }}
          fetch-depth: 0

      - name: Resolve release tag
        id: tag
        run: |
          TAG=$(git tag --points-at HEAD | grep '^v' | head -1)
          if [ -z "$TAG" ]; then
            echo "No v* tag at HEAD — skipping publish"
            echo "skip=true" >> "$GITHUB_OUTPUT"
          else
            echo "tag=${TAG}" >> "$GITHUB_OUTPUT"
            echo "skip=false" >> "$GITHUB_OUTPUT"
          fi

      - uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6
        if: steps.tag.outputs.skip == 'false'
        with:
          python-version: "3.14"
      - run: pip install build
        if: steps.tag.outputs.skip == 'false'
      - run: python -m build
        if: steps.tag.outputs.skip == 'false'
      - uses: pypa/gh-action-pypi-publish@cef221092ed1bacb1cc03d23a2d87d1d172e277b # release/v1
        if: steps.tag.outputs.skip == 'false'

      - name: Create GitHub Release
        if: steps.tag.outputs.skip == 'false'
        uses: softprops/action-gh-release@b4309332981a82ec1c5618f44dd2e27cc8bfbfda # v3
        with:
          tag_name: ${{ steps.tag.outputs.tag }}
          generate_release_notes: true
          draft: false
          prerelease: ${{ contains(steps.tag.outputs.tag, 'a') || contains(steps.tag.outputs.tag, 'b') || contains(steps.tag.outputs.tag, 'rc') }}
