name: Release to PyPI

on:
  release:
    types: [published]

permissions:
  contents: read

jobs:
  build-wheels:
    name: Build wheels (${{ matrix.target }})
    runs-on: ${{ matrix.runner }}
    strategy:
      matrix:
        include:
          # Linux x86_64 — manylinux_2_17 for broad HPC compatibility (glibc >= 2.17)
          - runner: ubuntu-latest
            target: x86_64
            manylinux: manylinux_2_17
          # Linux aarch64 — cross-compiled
          - runner: ubuntu-latest
            target: aarch64
            manylinux: manylinux_2_17
          # Linux ppc64le — Frontier/Summit compute nodes
          - runner: ubuntu-latest
            target: ppc64le
            manylinux: manylinux_2_17
          # macOS universal2 — fat binary covering both Intel and Apple Silicon
          - runner: macos-latest
            target: universal2-apple-darwin
            manylinux: ""
          # Windows x86_64
          - runner: windows-latest
            target: x86_64
            manylinux: ""
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: "3.12"
      - uses: dtolnay/rust-toolchain@stable
      - name: Build wheel
        uses: PyO3/maturin-action@v1
        with:
          target: ${{ matrix.target }}
          manylinux: ${{ matrix.manylinux || 'auto' }}
          args: --release --out dist
      - uses: actions/upload-artifact@v4
        with:
          name: wheels-${{ matrix.target }}-${{ matrix.runner }}
          path: dist/

  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
      - uses: actions/upload-artifact@v4
        with:
          name: sdist
          path: dist/

  publish-pypi:
    needs: [build-wheels, build-sdist]
    runs-on: ubuntu-latest
    environment: pypi
    permissions:
      id-token: write
    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: pypa/gh-action-pypi-publish@release/v1

  publish-crates:
    runs-on: ubuntu-latest
    environment: crates
    steps:
      - uses: actions/checkout@v4
      - uses: dtolnay/rust-toolchain@stable
      - name: Publish to crates.io
        env:
          CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
        run: |
          if ! cargo publish --allow-dirty 2>&1 | tee /tmp/publish.log; then
            if grep -q "already exists" /tmp/publish.log; then
              echo "Version already published to crates.io — skipping"
            else
              exit 1
            fi
          fi
