name: Publish

on:
  push:
    tags:
      - "v[0-9]+.[0-9]+.[0-9]+"

env:
  CARGO_TERM_COLOR: always

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

    steps:
      - uses: actions/checkout@v4

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

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

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

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