#!/usr/bin/env bash
# memory-save.sh  -  v6.2.E
#
# Writes a single per-repo memory file and updates the MEMORY.md index.
# Called by Phase 7's synthesis step (or any user skill that wants to
# persist a finding). Opt-in via prefs.global.perRepoMemory.
#
# Usage:
#   memory-save.sh <project-root> <type> <slug> <body-file>
#
#   type     = user | feedback | project | reference
#   slug     = kebab-case filename fragment (e.g. "audit-exhaustiveness")
#   body-file= path to a file containing the frontmatter-wrapped memory body
#              (or "-" to read body from stdin)
#
# Writes to $PROJECT_ROOT/.multi-agent/memory/<type>_<slug>.md and prepends
# a bullet to MEMORY.md. Idempotent  -  overwriting an existing slug replaces
# the file but leaves the index entry position unchanged.

set -euo pipefail

PROJECT_ROOT="${1:?usage: memory-save.sh <project-root> <type> <slug> <body-file|->}"
TYPE="${2:?missing type}"
SLUG="${3:?missing slug}"
BODY_SRC="${4:?missing body file (or '-')}"

case "$TYPE" in
  user|feedback|project|reference) ;;
  *) echo "memory-save: invalid type '$TYPE' (expected user|feedback|project|reference)" >&2; exit 1 ;;
esac

[[ "$SLUG" =~ ^[a-z0-9][a-z0-9-]*$ ]] || { echo "memory-save: invalid slug '$SLUG' (kebab-case [a-z0-9-])" >&2; exit 1; }

MEM_DIR="$PROJECT_ROOT/.multi-agent/memory"
MEM_INDEX="$MEM_DIR/MEMORY.md"
FILE="$MEM_DIR/${TYPE}_${SLUG}.md"

mkdir -p "$MEM_DIR"

# Gitignore guard  -  never commit memory to the repo.
GITIGNORE="$PROJECT_ROOT/.multi-agent/.gitignore"
if [ ! -f "$GITIGNORE" ]; then
  cat > "$GITIGNORE" <<'GI'
# Per-repo memory is local-only  -  never commit.
memory/
GI
fi

if [ "$BODY_SRC" = "-" ]; then
  body="$(cat)"
else
  [ -f "$BODY_SRC" ] || { echo "memory-save: body file '$BODY_SRC' not found" >&2; exit 1; }
  body="$(cat "$BODY_SRC")"
fi

printf '%s\n' "$body" > "$FILE"

# Derive index entry: use the first-line description (or slug as fallback).
description=$(awk '/^description:/ {sub(/^description: */, ""); gsub(/^"|"$/, ""); print; exit}' "$FILE" || true)
[ -n "$description" ] || description="$SLUG"

# Strip existing index line for this file (idempotent), then append new line.
if [ -f "$MEM_INDEX" ]; then
  grep -v "](${TYPE}_${SLUG}\.md)" "$MEM_INDEX" > "${MEM_INDEX}.tmp" || true
  mv "${MEM_INDEX}.tmp" "$MEM_INDEX"
else
  printf '# Per-repo memory index\n\n' > "$MEM_INDEX"
fi

title=$(awk '/^name:/ {sub(/^name: */, ""); gsub(/^"|"$/, ""); print; exit}' "$FILE" || true)
[ -n "$title" ] || title="$SLUG"

printf -- '- [%s](%s_%s.md)  -  %s\n' "$title" "$TYPE" "$SLUG" "$description" >> "$MEM_INDEX"

printf 'memory-save: wrote %s\n' "$FILE"
exit 0
