name: Release

on:
  push:
    tags: ["v[0-9]*"]

permissions:
  contents: write

env:
  CARGO_TERM_COLOR: always

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v5
      - uses: dtolnay/rust-toolchain@stable
      - uses: Swatinem/rust-cache@v2
      - run: cargo test

  publish-crate:
    needs: test
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v5
      - uses: dtolnay/rust-toolchain@stable
      - uses: Swatinem/rust-cache@v2
      - run: cargo publish 2>&1 | tee /tmp/cargo-publish.log || grep -q 'already uploaded' /tmp/cargo-publish.log
        env:
          CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}

  build-pypi:
    needs: test
    strategy:
      fail-fast: false
      matrix:
        include:
          - os: ubuntu-latest
            target: x86_64-unknown-linux-gnu
          - os: ubuntu-latest
            target: aarch64-unknown-linux-gnu
          - os: macos-26-intel
            target: x86_64-apple-darwin
          - os: macos-latest
            target: aarch64-apple-darwin
          - os: windows-latest
            target: x86_64-pc-windows-msvc
    runs-on: ${{ matrix.os }}
    steps:
      - uses: actions/checkout@v5
      - uses: dtolnay/rust-toolchain@stable
      - uses: Swatinem/rust-cache@v2
      - uses: PyO3/maturin-action@v1
        with:
          command: build
          manylinux: auto
          args: --release --features python --target ${{ matrix.target }}
      - uses: actions/upload-artifact@v4
        with:
          name: wheels-${{ matrix.target }}
          path: target/wheels/*.whl

  build-sdist:
    needs: test
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v5
      - uses: PyO3/maturin-action@v1
        with:
          command: sdist
          args: --out dist
      - uses: actions/upload-artifact@v4
        with:
          name: sdist
          path: dist/*.tar.gz

  publish-pypi:
    needs: [build-pypi, build-sdist]
    runs-on: ubuntu-latest
    steps:
      - uses: actions/download-artifact@v4
        with:
          pattern: wheels-*
          merge-multiple: true
          path: dist/
      - uses: actions/download-artifact@v4
        with:
          name: sdist
          path: dist/
      - uses: astral-sh/setup-uv@v4
      - run: uv publish --check-url https://pypi.org/simple/ dist/*
        env:
          UV_PUBLISH_TOKEN: ${{ secrets.PYPI_API_TOKEN }}

  github-release:
    needs: [publish-crate, publish-pypi]
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v5
      - uses: softprops/action-gh-release@v2
        with:
          generate_release_notes: true
