name: Release

on:
  push:
    branches: [main]

jobs:
  bump-and-tag:
    runs-on: ubuntu-latest
    # Skip if the commit was made by this workflow
    if: "!startsWith(github.event.head_commit.message, 'chore: bump version')"
    permissions:
      contents: write
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0
          token: ${{ secrets.PAT }}

      - name: Determine bump type from commits
        id: bump
        run: |
          # Look at commits since the last tag
          LAST_TAG=$(git describe --tags --abbrev=0 2>/dev/null || echo "")
          if [ -z "$LAST_TAG" ]; then
            COMMITS=$(git log --pretty=format:"%s" HEAD)
          else
            COMMITS=$(git log --pretty=format:"%s" "${LAST_TAG}..HEAD")
          fi

          if echo "$COMMITS" | grep -qiE "^feat!|^fix!|^refactor!|BREAKING CHANGE"; then
            echo "type=major" >> "$GITHUB_OUTPUT"
          elif echo "$COMMITS" | grep -qiE "^feat"; then
            echo "type=minor" >> "$GITHUB_OUTPUT"
          else
            echo "type=patch" >> "$GITHUB_OUTPUT"
          fi

      - uses: dtolnay/rust-toolchain@stable

      - name: Bump version in Cargo.toml
        id: version
        run: |
          CURRENT=$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -1)
          IFS='.' read -r MAJOR MINOR PATCH <<< "$CURRENT"

          case "${{ steps.bump.outputs.type }}" in
            major) MAJOR=$((MAJOR + 1)); MINOR=0; PATCH=0 ;;
            minor) MINOR=$((MINOR + 1)); PATCH=0 ;;
            patch) PATCH=$((PATCH + 1)) ;;
          esac

          NEW="${MAJOR}.${MINOR}.${PATCH}"
          sed -i "s/^version = \"${CURRENT}\"/version = \"${NEW}\"/" Cargo.toml
          cargo update --workspace
          echo "new_version=${NEW}" >> "$GITHUB_OUTPUT"

      - name: Commit and tag
        run: |
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"
          git add Cargo.toml Cargo.lock
          git commit -m "chore: bump version to ${{ steps.version.outputs.new_version }}"
          git tag "v${{ steps.version.outputs.new_version }}"
          git push origin ${{ github.ref_name }} --tags
