name: Publish

on:
  push:
    tags:
      - 'v*'

permissions:
  contents: read

jobs:
  publish-crates-io:
    name: Publish to crates.io
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Install Rust
        uses: dtolnay/rust-toolchain@stable

      - name: Verify Cargo.toml version matches tag
        id: verify
        run: |
          TAG_VERSION=${GITHUB_REF#refs/tags/v}
          CARGO_VERSION=$(grep '^version' Cargo.toml | head -1 | cut -d '"' -f2)
          echo "Tag version: $TAG_VERSION"
          echo "Cargo version: $CARGO_VERSION"
          if [ "$TAG_VERSION" != "$CARGO_VERSION" ]; then
            echo "Error: Tag version ($TAG_VERSION) does not match Cargo.toml version ($CARGO_VERSION)"
            exit 1
          fi
          echo "version=$CARGO_VERSION" >> $GITHUB_OUTPUT

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

  publish-pypi:
    name: Publish to PyPI
    runs-on: ubuntu-latest
    needs: publish-crates-io
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Install Rust
        uses: dtolnay/rust-toolchain@stable

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

      - name: Install maturin
        run: pip install maturin

      - name: Build and publish wheels
        env:
          MATURIN_PYPI_TOKEN: ${{ secrets.PYPI_API_TOKEN }}
        run: |
          maturin publish \
            --username __token__ \
            --password "$MATURIN_PYPI_TOKEN" \
            --interpreter python3.10 \
            --interpreter python3.11 \
            --interpreter python3.12 \
            --interpreter python3.13

  publish-docs:
    name: Publish docs.rs
    runs-on: ubuntu-latest
    needs: publish-crates-io
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Install Rust
        uses: dtolnay/rust-toolchain@stable

      - name: Verify docs build
        run: cargo doc --no-deps

      # docs.rs builds automatically from crates.io publish
      # This step just validates docs compile before release
