name: Deploy to PyPI

on:
  release:
    types: [published]
  push:
    branches: [main]
  pull_request:
    branches: [main]
  workflow_dispatch:

concurrency:
  group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
  cancel-in-progress: true

jobs:
  test_bindings:
    name: Test Python bindings
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
        with:
          submodules: recursive
      - uses: actions/setup-python@v4
        name: Install Python
        with:
          python-version: "3.9"
      - name: Install package
        run: |
          pip install -U pip setuptools wheel
          pip install .[tests]
      - name: Test package
        run: pytest test/python

  build_sdist:
    name: Build source distribution
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
        with:
          submodules: recursive
      - uses: actions/setup-python@v4
        name: Install Python
        with:
          python-version: "3.9"
      - name: Install dependencies
        run: pip install -q build
      - name: Build sdist
        run: python -m build --sdist
      - name: Install sdist
        run: pip install --verbose dist/*.tar.gz
        env:
          CC: "gcc-10"
          CXX: "g++-10"
      - uses: actions/upload-artifact@v3
        with:
          path: dist/*.tar.gz

  build_wheels:
    name: Build ${{ matrix.config.os }}-${{ matrix.config.arch }} wheels
    needs: [test_bindings, build_sdist]
    runs-on: ${{ matrix.config.os }}
    strategy:
      fail-fast: false
      matrix:
        config:
          - { os: ubuntu-latest, arch: x64 }
          - { os: macos-latest, arch: x64 }
          - { os: macos-latest, arch: arm64 }
          - { os: windows-latest, arch: x64 }
    steps:
      - uses: actions/checkout@v3
        with:
          submodules: recursive
      - uses: ilammy/msvc-dev-cmd@v1
      - name: Set Architecture to arm64 if necessary
        if: ${{ matrix.config.arch == 'arm64' }}
        run: echo "CIBW_ARCHS_MACOS=arm64" >> $GITHUB_ENV
      - name: Build wheels
        uses: pypa/cibuildwheel@v2.12.1
      - uses: actions/upload-artifact@v3
        with:
          path: ./wheelhouse/*.whl

  upload_pypi:
    name: Upload dists to PyPi
    needs: [build_wheels, build_sdist]
    runs-on: ubuntu-latest
    if: github.event_name == 'release' && github.event.action == 'published'
    steps:
      - uses: actions/download-artifact@v3
        with:
          name: artifact
          path: dist
      - uses: pypa/gh-action-pypi-publish@release/v1
        with:
          user: __token__
          password: ${{ secrets.PYPI_TOKEN }}
