name: Publish Rust SDK

on:
  push:
    tags:
      - "v*"

env:
  CARGO_TERM_COLOR: always

jobs:
  publish:
    name: Publish to Crates.io
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v4
        with:
          persist-credentials: false

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

      - name: Install protoc
        run: sudo apt-get update && sudo apt-get install -y protobuf-compiler

      - name: Check version match (tag vs Cargo.toml)
        run: |
          # Extract version (e.g. v0.1.0 -> 0.1.0)
          TAG_VERSION=${GITHUB_REF#refs/tags/v}
          CARGO_VERSION=$(grep "^version" Cargo.toml | head -n 1 | cut -d '"' -f 2)

          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

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