#!/bin/bash
# M3 v8：用正确的 base_generation=1 下发 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（base_generation=1）==="
PAYLOAD='{"base_generation":1,"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"}}]}'
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',{}))[:200])"

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. 实例 config_state ==="
curl -sS -H "$AUTH" "$BASE/api/v1/instances/$INST" | python3 -c "
import sys,json
d=json.load(sys.stdin).get('instance',json.load(open('/dev/null')) if False else json.load(sys.stdin))
print('config_state:',d.get('config_state'))
print('desired_gen:',d.get('desired_config_generation'))
print('applied_gen:',d.get('applied_config_generation'))
print('last_error:',d.get('last_error','')[:200])"

echo "=== 5. 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 "=== 6. friend.log llm-proxy 相关 ==="
docker exec $C sh -c 'grep -i "llm-proxy\|39527\|plugin.*start\|plugin.*fail" /var/lib/friend/logs/friend.log 2>/dev/null' | tail -10
echo DONE
