name: Publish to crates.io

on:
  push:
    tags:
      - 'v*'

jobs:
  publish:
    name: Publish
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

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

      - name: Verify version matches tag
        run: |
          TAG=${GITHUB_REF#refs/tags/v}
          CARGO_VERSION=$(grep '^version = ' Cargo.toml | head -1 | sed 's/version = "\(.*\)"/\1/')
          if [ "$TAG" != "$CARGO_VERSION" ]; then
            echo "Tag version ($TAG) does not match Cargo.toml version ($CARGO_VERSION)"
            exit 1
          fi

      - name: Run tests
        run: cargo test --verbose

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