#!/bin/bash
C=$(docker ps --format "{{.Names}}" | grep "friend-deploy" | head -1)
FT=$(docker exec postgres_db psql -U knowledge -d yunwoai -t -A -c "SELECT friend_token FROM user_friend_agents WHERE instance_id='friend-abc1d454';")

echo "=== 1. 模型列表（用 curl 替代 wget）==="
# 容器内可能没有 curl，先试 host curl 经 docker exec
docker exec $C sh -c "wget -q -O /tmp/ml.json --header='Authorization: Bearer $FT' 'http://127.0.0.1:8000/api/llm/channels/1/models' 2>/dev/null; wc -c /tmp/ml.json; cat /tmp/ml.json | head -c 2000"
echo

echo "=== 2. 用 host curl 经 tunnel 调 ==="
TOKEN="dev-admin-token"
INST="friend-abc1d454"
# 先创建 tunnel
TUN=$(curl -sS -X POST -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  -d '{"instance_id":"'$INST'","ttl_seconds":300}' \
  "http://127.0.0.1:19088/api/v1/instances/$INST/tunnels" 2>/dev/null)
echo "tunnel: $(echo $TUN | head -c 100)"
COOKIE=$(echo "$TUN" | python3 -c "import sys,json;d=json.load(sys.stdin);print(d.get('tunnel_cookie',''))" 2>/dev/null)
echo "cookie: ${COOKIE:0:30}..."

echo "=== 3. 经 tunnel 列模型 ==="
curl -sS -m 10 -H "Cookie: friend-tunnel=$COOKIE" \
  -H "Authorization: Bearer $FT" \
  "http://127.0.0.1:19088/panel/$INST/api/llm/channels/1/models" 2>/dev/null | python3 -c "
import sys,json
try:
    for m in json.load(sys.stdin):
        r=m.get('runtime') or {}
        print(m.get('id'), m.get('model_key'), 'state:', r.get('state'))
except Exception as e: print('err:', e, sys.stdin.read()[:200])
"

echo "=== 4. 现有路由 ==="
curl -sS -m 10 -H "Cookie: friend-tunnel=$COOKIE" \
  -H "Authorization: Bearer $FT" \
  "http://127.0.0.1:19088/panel/$INST/api/llm/routes" 2>/dev/null | python3 -c "
import sys,json
try:
    for r in json.load(sys.stdin):
        cands = r.get('candidates') or []
        print(r.get('id'), r.get('purpose'), 'candidates:', [(c.get('model_key'),c.get('channel_model_id')) for c in cands])
except Exception as e: print('err:', e, sys.stdin.read()[:200])
"
