name: Publish to crates.io

on:
  release:
    types: [created]

jobs:
  publish:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v6

      - uses: dtolnay/rust-toolchain@stable

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

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

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