name: Build and Publish Wheels

on:
  push:
    tags: ["v*"]

env:
  CARGO_TERM_COLOR: always

jobs:
  publish-crate-to-crates-io:
    name: Publish Crate to Crates.io
    runs-on: ubuntu-latest
    if: startsWith(github.ref, 'refs/tags/v')

    steps:
      - uses: actions/checkout@v5

      - name: Set up Rust
        uses: dtolnay/rust-toolchain@master
        with:
          toolchain: stable

      - name: Publish crate to crates.io
        run: cargo publish
        env:
          CARGO_REGISTRY_TOKEN: ${{ secrets.CRATES_IO_TOKEN }}

  build-wheels:
    name: Build wheels (${{ matrix.os }} - ${{ matrix.arch }} - py${{ matrix.python-version }})
    needs: publish-crate-to-crates-io
    runs-on: ${{ matrix.os }}
    strategy:
      fail-fast: false
      matrix:
        python-version: ["3.13", "3.14"]
        os: [ubuntu-latest, macos-latest]
        include:
          - os: ubuntu-latest
            arch: x86_64
            target: x86_64-unknown-linux-gnu
          - os: macos-latest
            arch: aarch64
            target: aarch64-apple-darwin
#          - os: windows-latest
#            arch: x86_64
#            target: x86_64-pc-windows-msvc

    steps:
      - uses: actions/checkout@v5

      - name: Set up Rust
        uses: dtolnay/rust-toolchain@stable
        with:
          toolchain: stable
          components: rustfmt, clippy

      - name: Install Python
        uses: actions/setup-python@v6
        with:
          python-version: "${{ matrix.python-version }}"

      - name: Install maturin
        run: pip install maturin

      - name: Build wheel
        run: |
          maturin build \
            --release \
            --locked \
            --target ${{ matrix.target }} \
            --features python \
            --interpreter python3

      - name: Upload wheels
        uses: actions/upload-artifact@v5
        with:
          name: wheels-${{ matrix.os }}-${{ matrix.arch }}-py${{ matrix.python-version }})
          path: target/wheels/*.whl

  # optional publish to PyPI
  publish-to-pypi:
    name: Publish to PyPI
    runs-on: ubuntu-latest
    needs: build-wheels
    if: startsWith(github.ref, 'refs/tags/v')
    steps:
      - uses: actions/checkout@v5
      - uses: actions/download-artifact@v6
        with:
          path: dist

      - name: Install Python + maturin
        uses: actions/setup-python@v6
        with:
          python-version: "3.14"

      - run: pip install maturin

      - name: Build source distribution (sdist)
        run: maturin sdist --out dist

      - name: Publish to PyPI
        env:
          MATURIN_PYPI_TOKEN: ${{ secrets.PYPI_API_TOKEN }}
        run: |
          # Upload built wheels from matrix builds
          find dist -name "*.whl" -exec maturin upload --skip-existing {} +
          # Upload source distribution produced above
          find dist -name "*.tar.gz" -exec maturin upload --skip-existing {} +
