#!/bin/bash
# M3 前置验证 v2：从容器侧反查实例，测 ingest 注入链路
BASE=http://10.168.3.36:19088

echo "=== 1. 枚举运行中的 friend-deploy 容器 ==="
C=$(docker ps --format '{{.Names}}' | grep '^friend-deploy-' | head -1)
echo "CONTAINER=$C"
[ -z "$C" ] && { echo NO_CONTAINER; exit 0; }

# 从 deployments 反查该容器对应的 instance_id
INST=$(curl -sS -H "Authorization: Bearer dev-admin-token" "$BASE/api/v1/instance-deployments" | python3 -c "
import sys,json
d=json.load(sys.stdin)
items=d if isinstance(d,list) else d.get('deployments',d.get('items',[]))
for x in items:
    if x.get('runtime_name')=='$C': print(x.get('instance_id','')); break")
echo "INSTANCE=$INST"

echo ""
echo "=== 2. 容器内插件与端口 ==="
docker exec $C sh -c 'ls /var/lib/friend/plugins/ 2>/dev/null'
docker exec $C sh -c 'cat /proc/net/tcp 2>/dev/null | awk "NR>1 {print \$2}" | while read a; do p=$((16#${a##*:})); [ $p -ge 7000 ] && echo LISTEN:$p; done' | sort -u | head

echo ""
echo "=== 3. 容器内直发 ingest 消息 ==="
ITOK=$(docker exec $C sh -c "grep api_auth_token /app/config/config.yaml" | awk '{print $2}')
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 INGEST_8787_FAILED

echo ""
echo "=== 4. 等 20s 后看主链节点是否新增（thinking）==="
sleep 20
MAIN=$(curl -sS -H "Authorization: Bearer dev-admin-token" "$BASE/api/v1/instances/$INST/tunnels" -X POST -H "Content-Type: application/json" -d '{}' | python3 -c "
import sys,json,urllib.parse as u
print(u.parse_qs(u.urlparse(json.load(sys.stdin)['url']).query)['__friend_tunnel'][0])")
ITOK2=$(docker exec $C sh -c "grep api_auth_token /app/config/config.yaml" | awk '{print $2}')
curl -sS --max-time 15 -H "Cookie: friend_cluster_tunnel=$MAIN" -H "Authorization: Bearer $ITOK2" "$BASE/panel/$INST/api/chains/main" | head -c 400
echo ""
DONE
