#!/usr/bin/env bash
# Append a one-liner [[fn_id]] — purpose to MEMORY.md after fn-constructor
# creates a new registry function. Idempotent: skips if id already present.
# Used by /fn_claude step 5b (issue 0087, pieza 6).
#
# Usage: append_fn_to_memory.sh <fn_id> "<one-line purpose>"

set -euo pipefail

FN_ID="${1:-}"
PURPOSE="${2:-}"

if [ -z "$FN_ID" ] || [ -z "$PURPOSE" ]; then
    echo "usage: append_fn_to_memory.sh <fn_id> <purpose>" >&2
    exit 2
fi

MEM_DIR="${CLAUDE_MEMORY_DIR:-/home/lucas/.claude/projects/-home-lucas-fn-registry/memory}"
MEM_FILE="$MEM_DIR/MEMORY.md"

[ -d "$MEM_DIR" ] || { echo "memory dir missing: $MEM_DIR" >&2; exit 1; }
[ -f "$MEM_FILE" ] || { echo "MEMORY.md missing: $MEM_FILE" >&2; exit 1; }

# Per-function reference file slug
SLUG="reference_fn_${FN_ID}.md"
REF_FILE="$MEM_DIR/$SLUG"

# Idempotency: if already linked in MEMORY.md, exit 0
if grep -qF "[fn-$FN_ID]" "$MEM_FILE" 2>/dev/null; then
    echo "already in MEMORY.md: $FN_ID"
    exit 0
fi

# 1. Create reference memory file
cat > "$REF_FILE" <<EOF
---
name: fn-$FN_ID
description: Registry function $FN_ID — $PURPOSE
metadata:
  type: reference
---

Registry function: \`$FN_ID\`

$PURPOSE

Invoke via \`./fn run $FN_ID [args]\` or \`mcp__registry__fn_run id="$FN_ID"\`. Inspect with \`mcp__registry__fn_show id="$FN_ID"\` / \`mcp__registry__fn_code id="$FN_ID"\`.
EOF

# 2. Append index line to MEMORY.md
printf -- '- [%s](%s) — %s\n' "fn-$FN_ID" "$SLUG" "$PURPOSE" >> "$MEM_FILE"

echo "appended: $FN_ID -> $MEM_FILE"
