name: Deploy sdist and wheels

on:
  push:
  pull_request:
  release:
    types:
      - published

jobs:
  build_sdist:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout source
        uses: actions/checkout@v5

      - name: Create sdist
        shell: bash -l {0}
        run: |
          python -m pip install -q build
          python -m build -s

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

  build_wheels:
    name: "Build wheels on ${{ matrix.os }} ${{ matrix.arch }}"
    runs-on: ${{ matrix.os }}
    strategy:
      fail-fast: false
      matrix:
        include:
          - os: windows-2022
            arch: "AMD64"
          - os: windows-11-arm
            arch: "ARM64"
          - os: macos-13
            arch: "x86_64"
          - os: macos-14
            arch: "arm64"
          - os: "ubuntu-24.04-arm"
            arch: "aarch64"
          - os: "ubuntu-24.04"
            arch: "x86_64"

    steps:
      - uses: actions/checkout@v5
      - run: |
          git fetch --prune --unshallow

      - name: Build wheels
        uses: pypa/cibuildwheel@v3.1.4
        env:
          CIBW_SKIP: "cp39-* cp310-* *-manylinux_i686 *-musllinux_i686 *-musllinux_aarch64 *-win32"
          CIBW_ARCHS: "${{ matrix.arch }}"
          CIBW_TEST_SKIP: "*_arm64"
          CIBW_ENABLE: cpython-freethreading

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

  upload_to_pypi:
    needs: [build_sdist, build_wheels]
    runs-on: ubuntu-latest
    steps:
      - name: Download sdist artifact
        uses: actions/download-artifact@v5
        with:
          name: sdist
          path: dist
      - name: Download wheels artifact
        uses: actions/download-artifact@v5
        with:
          pattern: wheels-*
          merge-multiple: true
          path: dist
      - name: Publish package to Test PyPI
        if: github.event.action != 'published' && github.event_name == 'push' && startsWith(github.event.ref, 'refs/tags/v')
        uses: pypa/gh-action-pypi-publish@v1.13.0
        with:
          user: __token__
          password: ${{ secrets.test_pypi_password }}
          repository_url: https://test.pypi.org/legacy/
      - name: Publish package to PyPI
        if: github.event.action == 'published'
        uses: pypa/gh-action-pypi-publish@v1.13.0
        with:
          user: __token__
          password: ${{ secrets.pypi_password }}
