name: Build and publish to PyPI

on:
  release:
    types: [published]
  workflow_dispatch:

jobs:
  build-wheels:
    name: Build wheels (${{ matrix.target }} on ${{ matrix.os }})
    runs-on: ${{ matrix.os }}
    strategy:
      fail-fast: false
      matrix:
        include:
          - os: ubuntu-latest
            target: x86_64-unknown-linux-gnu
          - os: macos-13
            target: x86_64-apple-darwin
          - os: macos-14
            target: aarch64-apple-darwin
          - os: windows-latest
            target: x86_64-pc-windows-msvc

    steps:
    - uses: actions/checkout@v4

    - name: Build wheel
      uses: PyO3/maturin-action@v1
      env:
        PYO3_USE_ABI3_FORWARD_COMPATIBILITY: "1"
      with:
        command: build
        args: --release --out dist
        target: ${{ matrix.target }}

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

  build-sdist:
    runs-on: ubuntu-latest

    steps:
    - uses: actions/checkout@v4

    - name: Build source distribution
      uses: PyO3/maturin-action@v1
      env:
        PYO3_USE_ABI3_FORWARD_COMPATIBILITY: "1"
      with:
        command: sdist
        args: --out dist

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

  publish:
    runs-on: ubuntu-latest
    needs: [build-wheels, build-sdist]
    environment:
      name: pypi
      url: https://pypi.org/p/groggy
    permissions:
      id-token: write
      contents: read

    steps:
    - name: Download distribution artifacts
      uses: actions/download-artifact@v4
      with:
        merge-multiple: true
        path: dist

    - name: List built files
      run: ls -R dist

    - name: Publish to PyPI
      if: startsWith(github.ref, 'refs/tags/')
      uses: pypa/gh-action-pypi-publish@release/v1
      with:
        packages-dir: dist
