#!/bin/bash
# M3 v7：用正确的 changes 字段格式下发 llm-proxy 插件配置
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 plugin.config（changes 格式）==="
PAYLOAD=$(cat <<EOF
{
  "base_generation": 0,
  "issued_by": "yunwo-m3",
  "changes": [
    {
      "kind": "plugin.config",
      "resource_key": "llm-proxy",
      "value": {
        "api_key": "sk-yunwo-internal",
        "upstream_base": "http://10.200.0.20:3000",
        "listen_addr": "127.0.0.1:39527"
      }
    }
  ]
}
EOF
)
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 400; echo

echo "=== 2. 等 10s 后查 extensions 与插件配置 ==="
sleep 10
curl -sS -H "$AUTH" "$BASE/api/v1/instances/$INST/extensions" | python3 -c "
import sys,json
for e in json.load(sys.stdin):
    print(e.get('id'),'|',e.get('state'),'|',json.dumps(e.get('config',{}))[:150])"

echo "=== 3. 验证 39527 监听 ==="
docker exec $C sh -c 'cat /proc/net/tcp /proc/net/tcp6 2>/dev/null' | awk 'NR>1 {split($2,a,":"); p=strtonum("0x" a[2]); if (p==39527) print "39527_LISTENING"}'

echo "=== 4. LLM 模型健康状态 ==="
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])")
curl -sS --max-time 15 -H "Cookie: friend_cluster_tunnel=$TTOK" -H "Authorization: Bearer $ITOK" "$BASE/panel/$INST/api/llm/models" | python3 -c "
import sys,json
try:
    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 '')[:80])
except Exception as ex: print('parse_err',ex)"
echo DONE
