name: Publish to crates.io

on:
  release:
    types: [created]

env:
  CARGO_TERM_COLOR: always

jobs:
  publish:
    runs-on: ubuntu-latest

    steps:
    - uses: actions/checkout@v4

    - uses: actions-rs/toolchain@v1
      with:
        toolchain: stable
        profile: minimal

    - name: Get release info
      id: release_info
      run: |
        # Extract version from release tag (e.g., v0.1.0 -> 0.1.0)
        RELEASE_TAG="${{ github.event.release.tag_name }}"
        RELEASE_TITLE="${{ github.event.release.name }}"

        echo "tag=$RELEASE_TAG" >> $GITHUB_OUTPUT
        echo "title=$RELEASE_TITLE" >> $GITHUB_OUTPUT

        echo "Release tag: $RELEASE_TAG"
        echo "Release title: $RELEASE_TITLE"

    - name: Get current crate version
      id: crate_version
      run: |
        VERSION=$(cargo metadata --no-deps --format-version 1 | jq -r '.packages[0].version')
        echo "version=$VERSION" >> $GITHUB_OUTPUT
        echo "Crate version: $VERSION"

    - name: Verify versions match
      run: |
        RELEASE_TAG="${{ steps.release_info.outputs.tag }}"
        RELEASE_TITLE="${{ steps.release_info.outputs.title }}"
        CRATE_VERSION="${{ steps.crate_version.outputs.version }}"

        # Verify release tag matches crate version (with v prefix)
        if [ "$RELEASE_TAG" != "v$CRATE_VERSION" ]; then
          echo "Error: Release tag ($RELEASE_TAG) does not match crate version (v$CRATE_VERSION)"
          exit 1
        fi

        # Verify release title matches crate version
        if [ "$RELEASE_TITLE" != "v$CRATE_VERSION" ]; then
          echo "Error: Release title ($RELEASE_TITLE) does not match crate version (v$CRATE_VERSION)"
          exit 1
        fi

        echo "✓ Release tag verified: $RELEASE_TAG"
        echo "✓ Release title verified: $RELEASE_TITLE"
        echo "✓ Crate version verified: $CRATE_VERSION"

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