#!/bin/bash
#
# Git pre-commit hook: reject commits that don't bump the version in package.json.
# Install: git config core.hooksPath .githooks
#

STAGED=$(git diff --cached --name-only)

# If no staged files, nothing to check
if [ -z "$STAGED" ]; then
  exit 0
fi

# Allow commits that ONLY touch non-code files (docs, config, etc.)
CODE_CHANGED=false
for f in $STAGED; do
  case "$f" in
    *.ts|*.js|*.json|*.mdc)
      CODE_CHANGED=true
      break
      ;;
  esac
done

if [ "$CODE_CHANGED" = false ]; then
  exit 0
fi

# Check if package.json is in the staged files
if ! echo "$STAGED" | grep -q '^package\.json$'; then
  echo ""
  echo "  COMMIT REJECTED: package.json is not staged."
  echo "  Every code change requires a version bump in package.json."
  echo "  See: .cursor/rules/versioning.mdc"
  echo ""
  exit 1
fi

# Check if the "version" field was actually changed
VERSION_DIFF=$(git diff --cached -U0 package.json | grep -E '^\+.*"version"')

if [ -z "$VERSION_DIFF" ]; then
  echo ""
  echo "  COMMIT REJECTED: package.json is staged but the \"version\" field was not changed."
  echo "  Bump the version (MAJOR.MINOR.PATCH) before committing."
  echo "  See: .cursor/rules/versioning.mdc"
  echo ""
  exit 1
fi

exit 0
