name: Bump Patch Version on Merge to Main

on:
  push:
    branches:
      - main

jobs:
  bump-version:
    runs-on: ubuntu-latest
    # Skip if this push was itself the version bump commit (prevents infinite loop)
    if: "!contains(github.event.head_commit.message, '[skip ci]')"

    permissions:
      contents: write

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          # Need full git history and ability to push
          fetch-depth: 0
          token: ${{ secrets.GITHUB_TOKEN }}

      - name: Bump patch version in pyproject.toml
        id: bump
        run: |
          # Read current version
          CURRENT=$(grep '^version = ' pyproject.toml | sed 's/version = "\(.*\)"/\1/')
          echo "Current version: $CURRENT"

          # Split into parts and increment patch
          MAJOR=$(echo $CURRENT | cut -d. -f1)
          MINOR=$(echo $CURRENT | cut -d. -f2)
          PATCH=$(echo $CURRENT | cut -d. -f3)
          NEW_PATCH=$((PATCH + 1))
          NEW_VERSION="$MAJOR.$MINOR.$NEW_PATCH"
          echo "New version: $NEW_VERSION"

          # Write back to pyproject.toml
          sed -i "s/^version = \"$CURRENT\"/version = \"$NEW_VERSION\"/" pyproject.toml

          # Export for later steps
          echo "new_version=$NEW_VERSION" >> $GITHUB_OUTPUT

      - name: Commit and push bumped version
        run: |
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"
          git add pyproject.toml
          git commit -m "chore: bump version to ${{ steps.bump.outputs.new_version }} [skip ci]"
          git push
      - name: Tag the release
        run: |
          git tag "v${{ steps.bump.outputs.new_version }}"
          git push origin "v${{ steps.bump.outputs.new_version }}"
