name: Publish to crates.io

on:
  push:
    tags:
      - 'v*'  # 当推送以 'v' 开头的标签时触发 (如 v0.1.0, v1.0.0)

env:
  CARGO_TERM_COLOR: always

jobs:
  # 首先运行测试确保代码质量
  test:
    name: Test Suite
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v4
    
    - name: Install Rust
      uses: dtolnay/rust-toolchain@stable
      with:
        components: rustfmt, clippy
    
    - name: Cache dependencies
      uses: actions/cache@v4
      with:
        path: |
          ~/.cargo/bin/
          ~/.cargo/registry/index/
          ~/.cargo/registry/cache/
          ~/.cargo/git/db/
          target/
        key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
    
    - name: Format check
      run: cargo fmt --all -- --check
    
    - name: Clippy check
      run: cargo clippy --all-targets --all-features -- -D warnings
    
    - name: Run tests
      run: cargo test --verbose
    
    - name: Test examples
      run: cargo build --examples

  # 只有测试通过后才执行发布
  publish:
    name: Publish to crates.io
    needs: test
    runs-on: ubuntu-latest
    if: startsWith(github.ref, 'refs/tags/v')
    
    steps:
    - uses: actions/checkout@v4
    
    - name: Install Rust
      uses: dtolnay/rust-toolchain@stable
    
    - name: Cache dependencies
      uses: actions/cache@v4
      with:
        path: |
          ~/.cargo/bin/
          ~/.cargo/registry/index/
          ~/.cargo/registry/cache/
          ~/.cargo/git/db/
          target/
        key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
    
    - name: Verify tag version matches Cargo.toml
      run: |
        TAG_VERSION=${GITHUB_REF#refs/tags/v}
        CARGO_VERSION=$(grep -E '^version = ' Cargo.toml | sed 's/version = "\([^"]*\)"/\1/')
        echo "Tag version: $TAG_VERSION"
        echo "Cargo.toml 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 --token ${{ secrets.CRATES_IO_TOKEN }}
      env:
        CARGO_REGISTRY_TOKEN: ${{ secrets.CRATES_IO_TOKEN }}