#!/bin/bash
# M3 v20：模型已 healthy，重新注入并验证 LLM 真实回复
BASE=http://10.168.3.36:19088
INST=friend-48beca9b
C=friend-deploy-0acc642d-5c1
AUTH="Authorization: Bearer dev-admin-token"
CT="Content-Type: application/json"

ITOK=$(docker exec $C sh -c "grep api_auth_token /app/config/config.yaml" | awk '{print $2}')
TTOK=$(curl -sS --max-time 10 -X POST -H "$AUTH" -H "$CT" -d '{}' "$BASE/api/v1/instances/$INST/tunnels" | python3 -c "
import sys,json,urllib.parse as u
print(u.parse_qs(u.urlparse(json.load(sys.stdin)['url']).query)['__friend_tunnel'][0])")
api() { local p=$1; shift; curl -sS --max-time 60 -H "Cookie: friend_cluster_tunnel=$TTOK" -H "Authorization: Bearer $ITOK" "$BASE/panel/$INST$p" "$@"; }

echo "=== 1. 当前模型状态 ==="
api /api/llm/models | python3 -c "
import sys,json
for m in json.load(sys.stdin):
    r=m.get('runtime') or {}
    print(m.get('model_key'),'|',r.get('state'))"

echo "=== 2. 主链当前状态 ==="
MAIN=$(api /api/chains/main)
echo "$MAIN" | head -c 300; echo
MAINID=$(echo "$MAIN" | python3 -c "import sys,json; print(json.load(sys.stdin).get('id',''))")
echo "MAINID=$MAINID"

echo "=== 3. 注入新消息 ==="
TS=$(date -u +%Y-%m-%dT%H:%M:%SZ)
docker exec $C sh -c "wget -qO- --header='Authorization: Bearer $ITOK' --header='Content-Type: application/json' --post-data='{\"platform\":\"yunwo\",\"platform_user_id\":\"u97\",\"platform_chat_id\":\"chat97\",\"message_type\":\"text\",\"content\":{\"parts\":[{\"type\":\"text\",\"text\":\"请用一句话介绍你自己\"}]},\"timestamp\":\"$TS\"}' http://127.0.0.1:8787/ingest 2>&1"

echo "=== 4. 轮询节点（最多120s）==="
for i in $(seq 1 8); do
  sleep 15
  OUT=$(api "/api/chains/$MAINID/nodes")
  RAWLEN=${#OUT}
  INFO=$(echo "$OUT" | python3 -c "
import sys,json
try:
    d=json.load(sys.stdin)
    nodes=d if isinstance(d,list) else d.get('nodes',[])
    print(len(nodes),'|',','.join(n.get('type') for n in nodes))
except Exception as ex:
    print('parse_err', str(ex)[:60], 'rawlen=$RAWLEN')" 2>/dev/null)
  echo "[poll $i] $INFO"
  echo "$INFO" | grep -qE "transmission|tool_call|assistant" && {
    echo "--- 最后3个节点 ---"
    echo "$OUT" | python3 -c "
import sys,json
d=json.load(sys.stdin)
nodes=d if isinstance(d,list) else d.get('nodes',[])
for n in nodes[-3:]:
    print(n.get('seq'),n.get('type'),str(n.get('payload') or {})[:300])"
    break
  }
done

echo "=== 5. 最新 brain/llm 日志 ==="
docker exec $C sh -c 'grep -E "brain.think|llm\.call|llm\.success" /var/lib/friend/logs/friend.log 2>/dev/null' | tail -6
echo DONE
