#!/usr/bin/env bash
# Pre-populate commit messages with the active Metrum subtask ID.
# Reads the ID from .claude/current-subtask (per-developer, gitignored).
# Skips merges, squashes, amends/templates, and commits with an inline -m message.

set -eu

COMMIT_MSG_FILE="$1"
COMMIT_SOURCE="${2-}"

case "$COMMIT_SOURCE" in
  merge|squash|commit|template) exit 0 ;;
esac

existing=$(grep -v '^#' "$COMMIT_MSG_FILE" 2>/dev/null | tr -d '[:space:]' || true)
[ -n "$existing" ] && exit 0

repo_root=$(git rev-parse --show-toplevel 2>/dev/null || echo ".")
state_file="$repo_root/.claude/current-subtask"
[ -f "$state_file" ] || exit 0

active=$(tr -d '[:space:]' < "$state_file")
[ -n "$active" ] || exit 0

tmp_file="${COMMIT_MSG_FILE}.subtask-tmp"
{
  printf '#%s ' "$active"
  cat "$COMMIT_MSG_FILE"
} > "$tmp_file"
mv "$tmp_file" "$COMMIT_MSG_FILE"

exit 0
