name: Release to PyPI

on:
  push:
    tags: ["v*"]

jobs:
  # Run the full CI suite first — don't publish a broken release.
  ci:
    uses: ./.github/workflows/ci.yml

  build:
    needs: ci
    runs-on: ubuntu-latest

    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 --upgrade pip build

      - name: Build sdist and wheel
        run: python -m build

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

  publish:
    needs: build
    runs-on: ubuntu-latest

    # Required for PyPI trusted publishing (OIDC).
    permissions:
      id-token: write

    environment:
      name: pypi
      url: https://pypi.org/project/bristlenose/

    steps:
      - name: Download build artifacts
        uses: actions/download-artifact@v4
        with:
          name: dist
          path: dist/

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

  github-release:
    needs: publish
    runs-on: ubuntu-latest

    permissions:
      contents: write

    steps:
      - uses: actions/checkout@v4

      - name: Create GitHub Release
        env:
          GH_TOKEN: ${{ github.token }}
        run: gh release create "${{ github.ref_name }}" --generate-notes man/bristlenose.1

  notify-homebrew:
    needs: publish
    runs-on: ubuntu-latest

    steps:
      - name: Extract version from tag
        id: version
        run: echo "version=${GITHUB_REF_NAME#v}" >> "$GITHUB_OUTPUT"

      - name: Dispatch Homebrew tap update
        uses: peter-evans/repository-dispatch@v3
        with:
          token: ${{ secrets.HOMEBREW_TAP_TOKEN }}
          repository: cassiocassio/homebrew-bristlenose
          event-type: update-formula
          client-payload: '{"version": "${{ steps.version.outputs.version }}"}'
