name: Publish to crates.io

on:
  push:
    tags:
      - 'v*'
  workflow_dispatch:
    inputs:
      dry-run:
        description: 'Perform a dry run (do not actually publish)'
        required: false
        default: 'true'
        type: boolean

permissions:
  contents: write

env:
  CARGO_TERM_COLOR: always

jobs:
  publish:
    name: Publish
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4

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

      - name: Cache
        uses: Swatinem/rust-cache@v2

      - name: Get version from tag
        if: github.event_name == 'push'
        id: version
        run: |
          TAG_VERSION="${GITHUB_REF#refs/tags/v}"
          CARGO_VERSION=$(grep -m1 '^version' Cargo.toml | cut -d'"' -f2)
          if [ "$TAG_VERSION" != "$CARGO_VERSION" ]; then
            echo "Error: Tag version ($TAG_VERSION) does not match Cargo.toml version ($CARGO_VERSION)"
            exit 1
          fi
          echo "version=$CARGO_VERSION" >> $GITHUB_OUTPUT
          echo "Version verified: $CARGO_VERSION"

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

      - name: Dry run publish
        if: github.event_name == 'workflow_dispatch' && inputs.dry-run == true
        run: cargo publish --dry-run

      - name: Publish to crates.io
        if: github.event_name == 'push' || (github.event_name == 'workflow_dispatch' && inputs.dry-run == false)
        env:
          CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
        run: cargo publish

      - name: Create GitHub Release
        if: github.event_name == 'push'
        uses: softprops/action-gh-release@v2
        with:
          name: v${{ steps.version.outputs.version }}
          generate_release_notes: true
          draft: false
