#!/usr/bin/env bash
# M-INTEROCEPTION P4 gate: afferent input counters in act-stats (additive).
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-p4-XXXXXX)"
export HOME="$WORK/home"; mkdir -p "$HOME"
unset ENGRAM_STORE
fail=0

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

"$WORK/p4" > "$WORK/out.txt" 2>&1 || { echo "FAIL run"; cat "$WORK/out.txt"; fail=1; }
grep -oE 'aff_[a-z_]+":[0-9]+' "$WORK/out.txt" | sed 's/^/    /' | head -30

echo
echo "== assertions =="
python3 - "$WORK/out.txt" <<'PY'
import sys,re,json
S={}
for line in open(sys.argv[1]):
    m=re.match(r'(STATS\d) (\{.*\})',line.strip())
    if m: S[m.group(1)]=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
s0,s1,s2=S["STATS0"],S["STATS1"],S["STATS2"]
# after creation, before any query
check(s0["aff_node_creates"]==5, f"node_creates==5 (got {s0['aff_node_creates']})")
check(s0["aff_ise_ingests"]==2,  f"ise_ingests==2 (got {s0['aff_ise_ingests']})")
check(s0["aff_edge_creates"]==2, f"edge_creates==2 (got {s0['aff_edge_creates']})")
check(s0["aff_queries"]==0 and s0["aff_activations"]==0, "queries/activations start at 0")
# after 4 queries
check(s1["aff_queries"]==4, f"queries==4 (got {s1['aff_queries']})")
check(s1["aff_activations"]==4, f"activations==4 (got {s1['aff_activations']})")
check(s1["aff_node_creates"]==5 and s1["aff_ise_ingests"]==2 and s1["aff_edge_creates"]==2,
      "create counters unchanged by queries")
# after 3 more queries — monotonic
check(s2["aff_queries"]==7, f"queries==7 monotonic (got {s2['aff_queries']})")
check(s2["aff_activations"]==7, f"activations==7 monotonic (got {s2['aff_activations']})")
check(s2["aff_queries"]>s1["aff_queries"]>s0["aff_queries"], "queries strictly monotonic across readings")
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_p4_afferent.c" $RTSRC $SSLFLAGS \
    -lcurl -lssl -lcrypto -lpthread -lm -lm -o "$WORK/p4.san" 2>"$WORK/san_cc.log" || { echo "SAN COMPILE FAILED"; tail -25 "$WORK/san_cc.log"; fail=1; }
if [ -x "$WORK/p4.san" ]; then
  export ASAN_OPTIONS=detect_leaks=0
  "$WORK/p4.san" >/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 "====== P4 AFFERENT-COUNTERS GATE: PASS ======"; else echo "====== P4 AFFERENT-COUNTERS GATE: FAIL ======"; fi
rm -rf "$WORK"
exit $fail
