#!/usr/bin/env bash
# commit-msg — Optional commit-msg hook for Red Bear OS.
# Auto-prepends the current development phase to commit messages.
# Usage:
#   cp local/scripts/commit-msg .git/hooks/commit-msg
#   chmod +x .git/hooks/commit-msg
# The hook is OPT-IN. See local/docs/HOOKS.md.

set -euo pipefail

COMMIT_MSG_FILE="$1"
PHASE=""

# Detect current phase from the most recent "phase X.Y:" commit in log
detect_phase() {
    PHASE=$(git log --oneline -50 2>/dev/null | grep -oP 'phase \d+\.\d+' | head -1)
    [ -n "$PHASE" ] || PHASE="phase"
}

detect_phase
FIRST_LINE=$(head -1 "$COMMIT_MSG_FILE" 2>/dev/null)

# Already has phase prefix or is Revert — skip
echo "$FIRST_LINE" | grep -qE '^(phase [0-9]+\.[0-9]+):' && exit 0
echo "$FIRST_LINE" | grep -qE '^Revert ' && exit 0

# Empty or comment — skip
[ -z "$FIRST_LINE" ] && exit 0
echo "$FIRST_LINE" | grep -q '^#' && exit 0

# Prepend phase
sed -i "1s/^/${PHASE}: /" "$COMMIT_MSG_FILE"
exit 0
