#!/usr/bin/env bash
# M-INTEROCEPTION P5 gate: dream-recall builtin engram_dreams_json (honesty rail).
set -u
HERE="$(cd "$(dirname "$0")" && pwd)"
RTSRC="$("$HERE/../../scripts/el-runtime-sources.sh" "$HERE/../../lang/runtime")"
# The runtime is MULTI-FILE (lang/runtime/SOURCES). This harness used to link
# el_runtime.c + engram_store.c only, which stopped linking once el_runtime.c
# began calling into the other engram siblings. Unquoted on purpose: a list.
SSLFLAGS=""
if command -v brew >/dev/null 2>&1 && O="$(brew --prefix openssl@3 2>/dev/null)"; then
  SSLFLAGS="-I$O/include -L$O/lib"
fi
INC="$HERE/../../lang/runtime"
WORK="$(mktemp -d /tmp/engram-p5-XXXXXX)"
export HOME="$WORK/home"; mkdir -p "$HOME"
unset ENGRAM_STORE
fail=0

echo "== compile =="
gcc -O1 -std=c11 -I "$INC" "$HERE/test_interoception_p5_dreams.c" $RTSRC $SSLFLAGS \
    -lcurl -lssl -lcrypto -lpthread -lm -lm -o "$WORK/p5" 2>"$WORK/cc.log" || { echo "COMPILE FAILED"; cat "$WORK/cc.log"; rm -rf "$WORK"; exit 1; }

D="$WORK/d"; mkdir -p "$D"
"$WORK/p5" "$D" > "$WORK/out.txt" 2>&1 || { echo "FAIL run"; cat "$WORK/out.txt"; fail=1; }
cat "$WORK/out.txt" | sed 's/^/    /'

echo
echo "== assertions =="
python3 - "$WORK/out.txt" <<'PY'
import sys,re,json
L={}
for line in open(sys.argv[1]):
    line=line.strip()
    m=re.match(r'(BEFORE|AFTER) (\[.*\])',line)
    if m: L[m.group(1)]=json.loads(m.group(2)); continue
    m=re.match(r'PRUNED (\d+)',line)
    if m: L['PRUNED']=int(m.group(1)); continue
    m=re.match(r'SINCE (\d+) (\[.*\])',line)
    if m: L['SINCE']=json.loads(m.group(2))
rc=0
def check(c,msg):
    global rc; print(("  PASS: " if c else "  FAIL: ")+msg)
    if not c: rc=1
before_ids={d["id"] for d in L["BEFORE"]}
after_ids={d["id"] for d in L["AFTER"]}
since_ids={d["id"] for d in L["SINCE"]}
check(before_ids=={"cur_old","cur_mid","cur_recent"}, f"before prune: all 3 curiosity_scan, heartbeat excluded (got {sorted(before_ids)})")
check("hb_recent" not in before_ids, "heartbeat ISE never appears (not a dream)")
check(L["PRUNED"]==1, f"prune rotated out exactly the ancient ISE (pruned={L['PRUNED']})")
check(after_ids=={"cur_mid","cur_recent"}, f"after prune: rotated-out cur_old is ABSENT, not confabulated (got {sorted(after_ids)})")
check("cur_old" not in after_ids, "honesty rail: pruned dream is gone = 'I don't remember', never synthesized")
check(since_ids=={"cur_recent"}, f"since filter returns only events after the cutoff (got {sorted(since_ids)})")
# no fabrication: every returned id was one we seeded
seeded={"cur_old","cur_mid","cur_recent","hb_recent"}
allret=before_ids|after_ids|since_ids
check(allret<=seeded, f"no fabricated entries — every returned id was seeded ({sorted(allret)})")
sys.exit(rc)
PY
[ $? -ne 0 ] && fail=1

echo
echo "== ASan+UBSan =="
gcc -O1 -g -std=c11 -fsanitize=address,undefined -fno-sanitize-recover=undefined \
    -I "$INC" "$HERE/test_interoception_p5_dreams.c" $RTSRC $SSLFLAGS \
    -lcurl -lssl -lcrypto -lpthread -lm -lm -o "$WORK/p5.san" 2>"$WORK/san_cc.log" || { echo "SAN COMPILE FAILED"; tail -25 "$WORK/san_cc.log"; fail=1; }
if [ -x "$WORK/p5.san" ]; then
  export ASAN_OPTIONS=detect_leaks=0
  DS="$WORK/ds"; mkdir -p "$DS"
  "$WORK/p5.san" "$DS" >/dev/null 2>"$WORK/san.log"
  if grep -qiE 'runtime error|AddressSanitizer|Sanitizer|ERROR: ' "$WORK/san.log"; then
    echo "  FAIL: sanitizer findings:"; grep -iE 'runtime error|Sanitizer|ERROR' "$WORK/san.log" | head; fail=1
  else echo "  ok: ASan+UBSan clean"; fi
fi

echo
if [ "$fail" -eq 0 ]; then echo "====== P5 DREAM-RECALL GATE: PASS ======"; else echo "====== P5 DREAM-RECALL GATE: FAIL ======"; fi
rm -rf "$WORK"
exit $fail
