#!/bin/bash
# M3 v18：upstream=siliconflow + GLM-5.2 → 更新实例模型配置 → probe → ingest 全链路
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"

echo "=== 1. 重下发 llm-proxy 配置（upstream=siliconflow, base_gen=3）==="
PAYLOAD='{"base_generation":3,"issued_by":"yunwo-m3","changes":[{"operation":"set","kind":"plugin.config","resource_uid":"llm-proxy","value":{"api_key":"sk-ifxhukpepyemattqafhtllahmqdysrrhgzthozfmaerqtlgr","upstream_base":"https://api.siliconflow.cn/v1","listen_addr":"127.0.0.1:39527"}}]}'
RESP=$(curl -sS --max-time 15 -X POST -H "$AUTH" -H "$CT" -d "$PAYLOAD" "$BASE/api/v1/instances/$INST/config-transactions")
echo "$RESP" | head -c 250; echo

sleep 12

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 40 -H "Cookie: friend_cluster_tunnel=$TTOK" -H "Authorization: Bearer $ITOK" "$BASE/panel/$INST$p" "$@"; }

echo "=== 2. 直连 39527 验证代理（GLM-5.2）==="
docker exec $C sh -c "wget -S -T 60 -O- --header='Content-Type: application/json' --post-data='{\"model\":\"zai-org/GLM-5.2\",\"messages\":[{\"role\":\"user\",\"content\":\"reply ok\"}],\"max_tokens\":10}' http://127.0.0.1:39527/v1/chat/completions 2>&1 | tail -4"

echo "=== 3. 把实例模型改成真实模型名 zai-org/GLM-5.2 ==="
api "/api/llm/models/1" -X PUT -H "Content-Type: application/json" -d '{"model_key":"zai-org/GLM-5.2","upstream_model_id":"zai-org/GLM-5.2","display_name":"GLM-5.2","enabled":true}' | head -c 200; echo
api "/api/llm/models/2" -X DELETE > /dev/null 2>&1 || true

echo "=== 4. probe 模型恢复健康 ==="
api "/api/llm/models/1/probe" -X POST | head -c 250; echo

echo "=== 5. 模型状态 ==="
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'),'|',(r.get('last_error') or '')[:100])"

STATE=$(api /api/llm/models | python3 -c "
import sys,json
models=json.load(sys.stdin)
print(any((m.get('runtime') or {}).get('state')=='healthy' for m in models))")

echo "=== 6. ingest 注入并等 LLM 回复（healthy=$STATE）==="
if [ "$STATE" = "True" ]; then
  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"
  MAINID=c89441e6-1962-4048-807c-db4f011f9336
  for i in 1 2 3 4 5 6 7 8; do
    sleep 15
    OUT=$(api "/api/chains/$MAINID/nodes")
    INFO=$(echo "$OUT" | python3 -c "
import sys,json
nodes=json.load(sys.stdin)
print(len(nodes),'|',','.join(n.get('type') for n in nodes))" 2>/dev/null)
    echo "[poll $i] nodes=$INFO"
    echo "$INFO" | grep -qE "transmission|tool_call|assistant" && { echo "--- 最后节点 ---"; echo "$OUT" | python3 -c "
import sys,json
for n in json.load(sys.stdin)[-3:]:
    print(n.get('seq'),n.get('type'),str(n.get('payload') or {})[:300])"; break; }
  done
else
  echo "MODELS_STILL_NOT_HEALTHY"
fi

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