#!/bin/sh
# Prefill the commit editor from pending Claude commit messages (one-shot).
#
# Claude sessions save suggestions with `~/.config/git/claude-commit-msg save` -- one file per
# message under $(git rev-parse --git-path CLAUDE_COMMIT_MSG.d)/, tagged with the paths it
# describes. On the next `git commit` / lazygit `C` this pastes the message(s) whose paths are
# part of the commit above git's comment block, then consumes them (moved to used/). Several
# sessions can hand off in parallel without overwriting each other.
#
# Falls back to the legacy single file $(git rev-parse --git-path CLAUDE_COMMIT_MSG) when the
# CLI is not deployed on this host (not re-stowed yet). Never exits non-zero: a helper problem
# must not abort a commit.
msg_file=$1
source=$2

# Only prefill a fresh editor session -- skip -m/-F (message), merge, squash, amend (commit).
case "$source" in
    ""|template) ;;
    *) exit 0 ;;
esac

cli="$HOME/.config/git/claude-commit-msg"
if [ -f "$cli" ] && command -v python3 >/dev/null 2>&1; then
    python3 "$cli" prefill "$msg_file" "$source"
    exit 0
fi

# --- legacy fallback: the single one-shot file ---
suggestion=$(git rev-parse --git-path CLAUDE_COMMIT_MSG)
[ -s "$suggestion" ] || exit 0

tmp=$(mktemp) || exit 0
{ cat "$suggestion"; printf '\n'; cat "$msg_file"; } > "$tmp" &&
    mv "$tmp" "$msg_file" &&
    mv "$suggestion" "$suggestion.last"
exit 0
