#!/usr/bin/env bash
# M-2: Pre-fix sibling search reminder (soft warning)
# Triggers on Edit/Write of .rs/.slint files containing function definitions.
# Reminds agent to grep for the function name before editing.
set -uo pipefail
INPUT=$(cat)
TOOL=$(echo "$INPUT" | python -c 'import sys,json; print(json.load(sys.stdin).get("tool_name",""))')
[[ "$TOOL" != "Edit" && "$TOOL" != "Write" ]] && { echo '{}'; exit 0; }

FILE=$(echo "$INPUT" | python -c 'import sys,json; t=json.load(sys.stdin).get("tool_input",{}); print(t.get("file_path","") or t.get("path",""))')
case "$FILE" in *.rs|*.slint) ;; *) echo '{}'; exit 0 ;; esac

CONTENT=$(echo "$INPUT" | python -c 'import sys,json; t=json.load(sys.stdin).get("tool_input",{}); print(t.get("new_string","") or t.get("content",""))')
FN=$(echo "$CONTENT" | grep -oE '\bfn [a-z_][a-z0-9_]*\b' | awk '{print $2}' | head -1)
[[ -z "$FN" ]] && { echo '{}'; exit 0; }

# Check if a Grep for this function name already happened in this session
TRANSCRIPT=$(echo "$INPUT" | python -c 'import sys,json; print(json.load(sys.stdin).get("transcript_path",""))' 2>/dev/null || echo "")
if [[ -n "$TRANSCRIPT" && -f "$TRANSCRIPT" ]] && grep -q "\"pattern\".*$FN" "$TRANSCRIPT" 2>/dev/null; then
  echo '{}'; exit 0
fi
cat <<EOF
{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"allow","additionalContext":"Pre-fix sibling-search reminder (M-2): editing fn $FN -- have you grepped for '$FN' across crates/app/src and crates/app/ui this session? See CLAUDE.md 'Pre-fix sibling search' rule."}}
EOF
