name: Publish to crates.io

on:
  push:
    tags:
      - 'v*'

jobs:
  test:
    name: Test before publishing
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - uses: dtolnay/rust-toolchain@stable

      - name: Run tests
        run: cargo test --lib --test integration

      - name: Check formatting
        run: cargo fmt --check

      - name: Run clippy
        run: cargo clippy --all-targets -- -D warnings

  publish:
    name: Publish to crates.io
    needs: test
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - uses: dtolnay/rust-toolchain@stable

      - name: Verify version matches tag
        run: |
          VERSION=$(grep '^version' Cargo.toml | head -1 | sed 's/version = "//;s/".*//')
          TAG=${GITHUB_REF#refs/tags/}
          TAG_VERSION=${TAG#v}
          if [ "$VERSION" != "$TAG_VERSION" ]; then
            echo "Error: Cargo.toml version ($VERSION) doesn't match tag ($TAG_VERSION)"
            exit 1
          fi
          echo "✓ Version matches: $VERSION"

      - name: Publish dry-run
        run: cargo publish --dry-run

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

      - name: Wait for crates.io to index
        run: sleep 10

      - name: Create GitHub Release
        uses: softprops/action-gh-release@v1
        with:
          files: |
            README.md
            CHANGELOG.md
          body_path: CHANGELOG.md
          draft: false
          prerelease: false
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
