#!/usr/bin/env bash
# OPC 记忆 固定检索用例 + 防空转自检（快速、不经 agent LLM、绝不超时）
# 每个 case 直接打 /memory/search（agent 真实检索路径），断言向量库能搜到指定记忆。
set -uo pipefail
MEMAPI="http://127.0.0.1:17760"
PASS=0; FAIL=0; LINES=""

# case: agent | query | 期望命中的关键词
CASES=(
  "xiaozhen|小金 台球 助教|小金"
  "xiaozhen|慧慧 咖啡 邀约|慧慧"
)

check_case(){
  local agent="$1" query="$2" expect="$3"
  local out hit
  out=$(curl -s -m 25 -X POST "$MEMAPI/memory/search" -H 'Content-Type: application/json' \
        -d "{\"agent_id\":\"$agent\",\"query\":\"$query\",\"limit\":6}" 2>/dev/null)
  hit=$(echo "$out" | python3 -c "import sys,json
try:
 d=json.load(sys.stdin); r=d.get('results',[])
 exp=sys.argv[1]
 print('YES' if any(exp in (x.get('memory') or '') for x in r) else 'NO')
except: print('ERR')" "$expect" 2>/dev/null)
  if [ "$hit" = YES ]; then PASS=$((PASS+1)); LINES="$LINES\n  ✅ [$agent] 搜「$query」命中「$expect」(向量库)";
  else FAIL=$((FAIL+1)); LINES="$LINES\n  ❌ [$agent] 搜「$query」未命中「$expect」(=$hit)"; fi
}

for c in "${CASES[@]}"; do
  IFS='|' read -r a q e <<< "$c"
  check_case "$a" "$q" "$e"
done

# 防空转机制在线自检：连发 7 次，应出现 system_stop
spin_ok=NO
for i in 1 2 3 4 5 6 7; do
  r=$(curl -s -m 25 -X POST "$MEMAPI/memory/search" -H 'Content-Type: application/json' \
      -d "{\"agent_id\":\"_spincheck\",\"query\":\"自检$i\",\"limit\":1}" 2>/dev/null)
  echo "$r" | grep -q "system_stop" && spin_ok=YES
done
if [ "$spin_ok" = YES ]; then PASS=$((PASS+1)); LINES="$LINES\n  ✅ 防空转机制在线(连搜触发强制停止)";
else FAIL=$((FAIL+1)); LINES="$LINES\n  ❌ 防空转机制未触发"; fi

[ "$FAIL" -eq 0 ] && RESULT=PASS || RESULT=FAIL
echo -e "记忆检索用例: $PASS 过 / $FAIL 败$LINES"
echo "CASES_RESULT=$RESULT"
[ "$RESULT" = PASS ] && exit 0 || exit 1
