Documentation
name: Release and Publish

on:
  release:
    types: [published]

env:
  CARGO_TERM_COLOR: always

jobs:
  publish:
    name: Publish to crates.io
    runs-on: ubuntu-latest

    steps:
      - name: Checkout code
        uses: actions/checkout@v4

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

      - name: Cache cargo registry
        uses: actions/cache@v4
        with:
          path: |
            ~/.cargo/registry/index/
            ~/.cargo/registry/cache/
            ~/.cargo/git/db/
          key: ${{ runner.os }}-cargo-registry-${{ hashFiles('**/Cargo.lock') }}
          restore-keys: |
            ${{ runner.os }}-cargo-registry-

      - name: Cache cargo build
        uses: actions/cache@v4
        with:
          path: target/
          key: ${{ runner.os }}-cargo-build-${{ hashFiles('**/Cargo.lock') }}
          restore-keys: |
            ${{ runner.os }}-cargo-build-

      - name: Run tests
        run: cargo test --all-features

      - name: Check formatting
        run: cargo fmt --all -- --check

      - name: Run clippy
        run: cargo clippy --all-features -- -D warnings

      - name: Verify version matches tag
        run: |
          CARGO_VERSION=$(cargo metadata --no-deps --format-version 1 | jq -r '.packages[0].version')
          TAG_VERSION=${GITHUB_REF#refs/tags/v}
          echo "Cargo version: $CARGO_VERSION"
          echo "Tag version: $TAG_VERSION"
          if [ "$CARGO_VERSION" != "$TAG_VERSION" ]; then
            echo "Version mismatch! Cargo.toml version ($CARGO_VERSION) does not match tag ($TAG_VERSION)"
            exit 1
          fi

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