name: Python wheels

on:
  push:
    tags:
      - 'v*'
  pull_request:
    paths:
      - 'src/**'
      - 'Cargo.toml'
      - 'Cargo.lock'
      - 'pyproject.toml'
  workflow_dispatch:

concurrency:
  group: python-wheels-${{ github.ref }}
  cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}

permissions:
  contents: read

jobs:
  sdist:
    name: Build sdist
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Build sdist
        uses: PyO3/maturin-action@v1
        with:
          command: sdist
          args: --out dist

      - name: Validate sdist
        run: pipx run twine check --strict dist/*

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

  wheels:
    name: Build wheels (${{ matrix.os }}, ${{ matrix.target }})
    runs-on: ${{ matrix.os }}
    strategy:
      fail-fast: false
      matrix:
        include:
          - os: ubuntu-latest
            target: x86_64
          - os: ubuntu-22.04
            target: aarch64
            manylinux: 2_28
          - os: macos-15
            target: x86_64
          - os: macos-14
            target: aarch64
          - os: windows-latest
            target: x86_64
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-python@v5
        with:
          python-version: '3.12'

      - name: Build wheels
        uses: PyO3/maturin-action@v1
        with:
          target: ${{ matrix.target }}
          args: --release --out dist --find-interpreter
          manylinux: ${{ matrix.manylinux || 'auto' }}

      - name: Validate wheels
        if: matrix.target != 'aarch64' || runner.os != 'Linux'
        run: pipx run twine check --strict dist/*

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

  publish:
    name: Publish to PyPI
    needs: [sdist, wheels]
    runs-on: ubuntu-latest
    if: startsWith(github.ref, 'refs/tags/v')
    environment:
      name: pypi
      url: https://pypi.org/p/snapper-fmt
    permissions:
      id-token: write
    steps:
      - uses: actions/download-artifact@v4
        with:
          pattern: '{sdist,wheels-*}'
          merge-multiple: true
          path: dist/

      - name: Publish to PyPI
        uses: pypa/gh-action-pypi-publish@release/v1
