name: cibuildwheel
# https://docs.github.com/en/actions/reference/workflow-syntax-for-github-actions#concurrency
# https://docs.github.com/en/developers/webhooks-and-events/events/github-event-types#pullrequestevent
concurrency:
  group: wheel-${{ github.ref }}-${{ github.event.type }}
  cancel-in-progress: true

on: [push, pull_request]

jobs:
  build_wheels:
    name: Build wheels on ${{ matrix.os }} for ${{ matrix.arch }}
    runs-on: ${{ matrix.os }}
    strategy:
      fail-fast: false
      matrix:
        os: [ubuntu-latest, windows-2025, macos-15, macos-15-intel, ubuntu-24.04-arm]
        arch: [auto]
    steps:
    - uses: actions/checkout@v6
      with:
        fetch-depth: 0
    - name: Set up QEMU
      if: ${{ matrix.arch == 'aarch64' }}
      uses: docker/setup-qemu-action@v3
    - name: Build wheels
      uses: pypa/cibuildwheel@v3.3.0
      env:
        CIBW_ARCHS_LINUX: ${{ matrix.arch }}
    - uses: actions/upload-artifact@v6
      with:
        name: wheels-${{ matrix.os }}-${{ matrix.arch }}
        path: ./wheelhouse/*.whl

  build_sdist:
    name: Build source distribution
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v6
      with:
        fetch-depth: 0
    - uses: actions/setup-python@v6
      name: Install Python
      with:
        python-version: '3.9'
    - name: Build sdist
      run: |
        python -m pip install --upgrade pip setuptools build wheel
        python -m pip install numpy Cython
        python -m build -s -o dist/
    - uses: actions/upload-artifact@v6
      with:
        name: sdist
        path: dist/*.tar.gz

  upload_test_pypi:
    needs: [build_wheels, build_sdist]
    runs-on: ubuntu-latest
    steps:
      - uses: actions/download-artifact@v7
        with:
          name: sdist
          path: dist
      - uses: actions/download-artifact@v7
        with:
          pattern: wheels-*
          merge-multiple: true
          path: dist
      - uses: pypa/gh-action-pypi-publish@master
        # upload to Test PyPI for every commit on main branch
        if: github.event_name == 'push' && github.event.ref == 'refs/heads/main'
        with:
          user: __token__
          password: ${{ secrets.VISPY_TEST_PYPI_TOKEN }}
          repository_url: https://test.pypi.org/legacy/

  upload_pypi:
    needs: [build_wheels, build_sdist]
    runs-on: ubuntu-latest
    steps:
      - uses: actions/download-artifact@v7
        with:
          name: sdist
          path: dist

      - uses: actions/download-artifact@v7
        with:
          pattern: wheels-*
          merge-multiple: true
          path: dist
      - uses: pypa/gh-action-pypi-publish@master
        # upload to PyPI on every tag starting with 'v'
        if: github.event_name == 'push' && startsWith(github.event.ref, 'refs/tags/v')
        with:
          user: __token__
          password: ${{ secrets.VISPY_PYPI_TOKEN }}
