#!/usr/bin/env bash
# UserPromptSubmit hook: recordatorio compacto de patrones canonicos del registry.
# Inyectado como additionalContext en cada turno del usuario.
# Issue 0085 (hardening 2).
#
# NUNCA bloquea. Solo printf de additionalContext.

set -euo pipefail

# Resolve registry root (walks up from cwd)
resolve_root() {
    local d="${PWD}"
    while [ "$d" != "/" ]; do
        if [ -f "$d/registry.db" ]; then
            printf '%s' "$d"
            return 0
        fi
        d=$(dirname "$d")
    done
    return 1
}

ROOT=$(resolve_root) || exit 0

# Read input, extract session_id (UserPromptSubmit payload includes it)
INPUT=$(cat)
SESSION_ID=""
if command -v jq >/dev/null 2>&1; then
    SESSION_ID=$(printf '%s' "$INPUT" | jq -r '.session_id // ""' 2>/dev/null || true)
fi

# Count current pending proposals + recent violations for situational awareness
PROPOSALS_PENDING="?"
VIOLATIONS_24H="?"
CALLS_24H="?"
CAP_CREATED=0
CAP_USED=0
CAP_ORPHAN=0

if command -v sqlite3 >/dev/null 2>&1; then
    REG="$ROOT/registry.db"
    MON="$ROOT/projects/fn_monitoring/apps/call_monitor/operations.db"
    [ -f "$REG" ] && PROPOSALS_PENDING=$(sqlite3 "$REG" "SELECT COUNT(*) FROM proposals WHERE status='pending'" 2>/dev/null || echo "?")
    if [ -f "$MON" ]; then
        VIOLATIONS_24H=$(sqlite3 "$MON" "SELECT COUNT(*) FROM violations WHERE ts >= CAST(strftime('%s','now','-1 day') AS INTEGER)" 2>/dev/null || echo "?")
        CALLS_24H=$(sqlite3 "$MON" "SELECT COUNT(*) FROM calls WHERE ts >= CAST(strftime('%s','now','-1 day') AS INTEGER)" 2>/dev/null || echo "?")
        if [ -n "$SESSION_ID" ]; then
            sid_esc=$(printf '%s' "$SESSION_ID" | sed "s/'/''/g")
            CAP_CREATED=$(sqlite3 "$MON" "SELECT COUNT(*) FROM session_capability_growth WHERE session_id='$sid_esc'" 2>/dev/null || echo 0)
            CAP_USED=$(sqlite3 "$MON" "SELECT COUNT(*) FROM session_capability_growth WHERE session_id='$sid_esc' AND calls_in_session>0" 2>/dev/null || echo 0)
            CAP_ORPHAN=$(sqlite3 "$MON" "SELECT COUNT(*) FROM session_capability_growth WHERE session_id='$sid_esc' AND calls_in_session=0" 2>/dev/null || echo 0)
        fi
    fi
fi

REMINDER="REGISTRY-FIRST (issue 0085 telemetry active): "
REMINDER+="Inspect → mcp__registry__fn_search/show/code/uses/proposal. "
REMINDER+="Execute one fn → mcp__registry__fn_run or ./fn run. "
REMINDER+="Compose multi-fn → heredoc python IMPORTANDO del registry. "
REMINDER+="NUNCA sqlite3 registry.db directo (salvo schema/PRAGMA/COUNT/JOIN). "
REMINDER+="NUNCA reescribir inline logica que ya es funcion. "
REMINDER+="Si patron se repite >2x → propose nueva funcion via fn-constructor. "
REMINDER+="Estado: pending_proposals=${PROPOSALS_PENDING} violations_24h=${VIOLATIONS_24H} calls_24h=${CALLS_24H}. "
REMINDER+="CAPABILITY-GROWTH (issue 0086): created_this_session=${CAP_CREATED} used=${CAP_USED} orphan=${CAP_ORPHAN}. Si orphan>0 -> integra la funcion en el codigo o documenta por que se quedo huerfana. "
REMINDER+="Comando autocheck: /fn_claude."

jq -n --arg ctx "$REMINDER" '{
  hookSpecificOutput: {
    hookEventName: "UserPromptSubmit",
    additionalContext: $ctx
  }
}'
