# This workflow will upload a Python Package using Twine when a release is created
# For more information see: https://help.github.com/en/actions/language-and-framework-guides/using-python-with-github-actions#publishing-to-package-registries

# This workflow uses actions that are not certified by GitHub.
# They are provided by a third-party and are governed by
# separate terms of service, privacy policy, and support
# documentation.

name: Upload Python Package

on:
  workflow_dispatch:
  release:
    types: [published]

env:
  # UV_INDEX_STRATEGY: "unsafe-first-match"
  # UV_EXTRA_INDEX_URL: "https://download.pytorch.org/whl/cpu"
  PIP_EXTRA_INDEX_URL: "https://download.pytorch.org/whl/cpu"

jobs:
  build_wheels:
    name: Build wheels on ${{ matrix.os }}/${{ matrix.arch || '*' }}
    runs-on: ${{ matrix.os }}
    strategy:
      matrix:
        os: [ubuntu-22.04, windows-latest, macos-latest]

    steps:
      - uses: actions/checkout@v4

      - name: Build wheels
        uses: pypa/cibuildwheel@v2.21.3
        env:
          CIBW_ARCHS_MACOS: "x86_64 arm64"
          CIBW_ENVIRONMENT: PIP_EXTRA_INDEX_URL=https://download.pytorch.org/whl/cpu

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

  build_sdist:
    name: Build source distribution
    runs-on: ubuntu-22.04
    steps:
      - uses: actions/checkout@v2

      - name: Build sdist
        run: pipx run build --sdist

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

  PyPI:
    name: Upload to PyPI

    needs: [build_wheels, build_sdist]
    runs-on: ubuntu-22.04

    steps:
    - uses: actions/download-artifact@v4
      with:
        pattern: cibw-*
        path: dist
        merge-multiple: true
    - name: Publish package
      uses: pypa/gh-action-pypi-publish@v1.5.0
      with:
        user: __token__
        password: ${{ secrets.PYPI_API_TOKEN }}

        # password: ${{ secrets.TEST_PYPI_API_TOKEN }}
        # repository_url: https://test.pypi.org/legacy/

  Documentation:
    runs-on: ubuntu-22.04
    steps:
    - uses: actions/checkout@v3

    - uses: actions/setup-python@v4
      with:
        python-version: "3.9"
        cache: 'pip'

    - name: Install dependencies
      run: |
        python -m pip install --upgrade pip
        pip install '.[docs]'

    - name: Set up Git
      run: |
        git config user.name ${{ github.actor }}
        git config user.email ${{ github.actor }}@users.noreply.github.com

    - name: Build documentation
      run: |
        git fetch origin gh-pages
        mike deploy --push --no-redirect --update-aliases $GITHUB_REF_NAME latest
