#!/bin/bash
# M3 v14：诊断上游连通性 + 对比健康实例的 llm-proxy 配置
BASE=http://10.168.3.36:19088
AUTH="Authorization: Bearer dev-admin-token"
CT="Content-Type: application/json"
C=friend-deploy-0acc642d-5c1

echo "=== 1. 容器内测上游 10.200.0.20:3000 ==="
docker exec $C sh -c "wget -S -T 5 -O- http://10.200.0.20:3000/ 2>&1 | head -8"

echo ""
echo "=== 2. 宿主机测上游（对照）==="
wget -S -T 5 -O- http://10.200.0.20:3000/ 2>&1 | head -6 || true

echo ""
echo "=== 3. 找一个 LLM 正常的实例做对照 ==="
# yunwo-test-instance 或其他实例的 llm-proxy plugin.config
for INST in $(curl -sS -H "$AUTH" "$BASE/api/v1/instances" | python3 -c "
import sys,json
d=json.load(sys.stdin)
items=d if isinstance(d,list) else d.get('instances',[])
for i in items: print(i.get('id'))"); do
  CONF=$(curl -sS --max-time 8 -H "$AUTH" "$BASE/api/v1/instances/$INST/config" 2>/dev/null | python3 -c "
import sys,json
try:
    d=json.load(sys.stdin)
    res=d.get('resources') or d.get('config',{}).get('resources') or []
    for r in res:
        if r.get('kind')=='plugin.config' and 'llm-proxy' in str(r.get('resource_key','')+r.get('resource_uid','')):
            print(json.dumps(r.get('value',{}))[:200]); break
except Exception: pass" 2>/dev/null)
  [ -n "$CONF" ] && echo "$INST => $CONF"
done

echo ""
echo "=== 4. 本实例当前生效的 plugin.config ==="
curl -sS -H "$AUTH" "$BASE/api/v1/instances/friend-48beca9b/config" | python3 -c "
import sys,json
try:
    d=json.load(sys.stdin)
    res=d.get('resources') or d.get('config',{}).get('resources') or []
    if not res and isinstance(d,list): res=d
    found=False
    for r in res:
        if r.get('kind')=='plugin.config':
            print(r.get('resource_key') or r.get('resource_uid'),'=>',json.dumps(r.get('value',{}))[:250]); found=True
    if not found: print('(no plugin.config resources)', json.dumps(d)[:200])
except Exception as ex: print('parse_err',ex)"
echo DONE
