#!/bin/bash
# M3 v16：容器内直连公网 LLM 网关排查 502 根因
C=friend-deploy-0acc642d-5c1

echo "=== 1. 容器内 DNS 解析 ==="
docker exec $C sh -c 'nslookup llm.zhengcloud.ltd 2>&1 | head -6 || getent hosts llm.zhengcloud.ltd || echo NO_DNS_TOOL'

echo ""
echo "=== 2. 容器内直连上游 /v1/models ==="
docker exec $C sh -c "wget -S -T 15 -O- --header='Authorization: Bearer sk-1K64cmiw1jl2XVydF7u6PGATe66GJinAJgZfSSTtiDuKCpjJ' https://llm.zhengcloud.ltd/v1/models 2>&1 | tail -8"

echo ""
echo "=== 3. 容器内直连 chat/completions ==="
docker exec $C sh -c "wget -S -T 30 -O- --header='Authorization: Bearer sk-1K64cmiw1jl2XVydF7u6PGATe66GJinAJgZfSSTtiDuKCpjJ' --header='Content-Type: application/json' --post-data='{\"model\":\"glm-5-2\",\"messages\":[{\"role\":\"user\",\"content\":\"hi\"}],\"max_tokens\":20}' https://llm.zhengcloud.ltd/v1/chat/completions 2>&1 | tail -10"

echo ""
echo "=== 4. 本机对照测试同一网关 ==="
curl -sS --max-time 20 -H "Authorization: Bearer sk-1K64cmiw1jl2XVydF7u6PGATe66GJinAJgZfSSTtiDuKCpjJ" -H "Content-Type: application/json" -d '{"model":"glm-5-2","messages":[{"role":"user","content":"hi"}],"max_tokens":20}' https://llm.zhengcloud.ltd/v1/chat/completions | head -c 300

echo ""
echo "=== 5. llm-proxy 插件 stderr 最新错误 ==="
docker exec $C sh -c 'grep "plugin.stderr" /var/lib/friend/logs/friend.log 2>/dev/null' | grep -iE "error|fail|upstream" | tail -8

echo "=== 6. 本机查模型名是否正确 ==="
curl -sS --max-time 15 -H "Authorization: Bearer sk-1K64cmiw1jl2XVydF7u6PGATe66GJinAJgZfSSTtiDuKCpjJ" https://llm.zhengcloud.ltd/v1/models | python3 -c "
import sys,json
try:
    d=json.load(sys.stdin)
    ids=[m.get('id') for m in d.get('data',[])]
    print('total:',len(ids))
    print([i for i in ids if 'glm' in i.lower()][:8])
except Exception as ex: print('parse_err',ex)"
echo DONE
