#!/bin/sh

# Auto version bump based on conventional commit prefix.
# feat: / feat( → minor bump
# fix: / fix(   → patch bump
# Anything else → no bump

# Guard against recursive amend
if [ "$STORY_LOOM_SKIP_BUMP" = "1" ]; then
  exit 0
fi

# Read the subject line of the latest commit
COMMIT_MSG=$(git log -1 --pretty=%s)

# Determine bump level
BUMP_LEVEL=""
case "$COMMIT_MSG" in
  feat:*|feat\(*) BUMP_LEVEL="minor" ;;
  fix:*|fix\(*)   BUMP_LEVEL="patch" ;;
  *)              exit 0 ;;
esac

# Parse current version from pyproject.toml
PYPROJECT="pyproject.toml"
if [ ! -f "$PYPROJECT" ]; then
  exit 0
fi

CURRENT_VERSION=$(grep -m1 '^version = "' "$PYPROJECT" | sed 's/version = "\(.*\)"/\1/')
if [ -z "$CURRENT_VERSION" ]; then
  exit 0
fi

# Split version into parts
MAJOR=$(echo "$CURRENT_VERSION" | cut -d. -f1)
MINOR=$(echo "$CURRENT_VERSION" | cut -d. -f2)
PATCH=$(echo "$CURRENT_VERSION" | cut -d. -f3)

# Bump
if [ "$BUMP_LEVEL" = "minor" ]; then
  MINOR=$((MINOR + 1))
  PATCH=0
elif [ "$BUMP_LEVEL" = "patch" ]; then
  PATCH=$((PATCH + 1))
fi

NEW_VERSION="${MAJOR}.${MINOR}.${PATCH}"

# Update pyproject.toml
sed -i '' "s/^version = \"${CURRENT_VERSION}\"/version = \"${NEW_VERSION}\"/" "$PYPROJECT"

# Amend the commit with the version bump
git add "$PYPROJECT"
STORY_LOOM_SKIP_BUMP=1 git commit --amend --no-edit --no-verify
