name: Build and publish to PyPI

on:
  workflow_dispatch:
    inputs:
      repository:
        description: "PyPI repository to publish to"
        type: choice
        options:
          - testpypi
          - pypi
        default: testpypi
        required: true
  release:
    types: [published]

jobs:
  target:
    name: Resolve target repository
    runs-on: ubuntu-latest
    outputs:
      name: ${{ steps.pick.outputs.name }}
      url: ${{ steps.pick.outputs.url }}
    steps:
      - id: pick
        env:
          EVENT_NAME: ${{ github.event_name }}
          REPOSITORY: ${{ inputs.repository }}
        run: |
          if [ "$EVENT_NAME" = "release" ] || [ "$REPOSITORY" = "pypi" ]; then
            echo "name=pypi" >> "$GITHUB_OUTPUT"
            echo "url=https://upload.pypi.org/legacy/" >> "$GITHUB_OUTPUT"
          else
            echo "name=testpypi" >> "$GITHUB_OUTPUT"
            echo "url=https://test.pypi.org/legacy/" >> "$GITHUB_OUTPUT"
          fi

  build_sdist:
    name: Build sdist
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-python@v5
        with:
          python-version: "3.11"

      - name: Build sdist
        run: |
          python -m pip install --upgrade build
          python -m build --sdist

      - uses: actions/upload-artifact@v4
        with:
          name: dist-sdist
          path: dist/*.tar.gz

  build_wheels:
    name: Build wheel (${{ matrix.os }})
    runs-on: ${{ matrix.os }}
    strategy:
      fail-fast: false
      matrix:
        os: [ubuntu-latest, macos-latest, windows-latest]

    steps:
      - uses: actions/checkout@v4

      - name: Build wheels
        uses: pypa/cibuildwheel@v2.21.3
        env:
          CIBW_BUILD: "cp311-*"
          CIBW_SKIP: "*-musllinux* *_i686 *-win32"
          CIBW_MANYLINUX_X86_64_IMAGE: manylinux_2_28
          CIBW_BUILD_VERBOSITY: "1"

      - uses: actions/upload-artifact@v4
        with:
          name: dist-wheels-${{ matrix.os }}
          path: ./wheelhouse/*.whl

  publish:
    name: Publish to ${{ needs.target.outputs.name }}
    needs: [target, build_sdist, build_wheels]
    runs-on: ubuntu-latest
    environment: ${{ needs.target.outputs.name }}
    permissions:
      id-token: write
    steps:
      - uses: actions/download-artifact@v4
        with:
          pattern: dist-*
          merge-multiple: true
          path: dist

      - name: Publish to PyPI
        uses: pypa/gh-action-pypi-publish@release/v1
        with:
          repository-url: ${{ needs.target.outputs.url }}
          skip-existing: true