#!/bin/bash
MANAGER="http://127.0.0.1:19088"
TOKEN="dev-admin-token"

echo "=== 查找测试实例 Friend API token ==="
python3 << 'PYEOF'
import sqlite3
conn = sqlite3.connect("/opt/friend-cluster/data/friend-cluster-v1.db")
cur = conn.cursor()

# 列出 friend_instances 所有列
cur.execute("PRAGMA table_info(friend_instances)")
cols = [r[1] for r in cur.fetchall()]
print("Columns:", cols)

# 查看所有可能含 token 的字段
for col in cols:
    cl = col.lower()
    if 'token' in cl or 'panel' in cl or 'api' in cl or 'auth' in cl or 'secret' in cl:
        cur.execute(f"SELECT '{col}', {col} FROM friend_instances WHERE id='friend-4f864178'")
        for r in cur.fetchall():
            val = str(r[1])[:200] if r[1] else '(null)'
            print(f"  TEST {r[0]}: {val}")
        cur.execute(f"SELECT '{col}', {col} FROM friend_instances WHERE id='friend-043bd076'")
        for r in cur.fetchall():
            val = str(r[1])[:200] if r[1] else '(null)'
            print(f"  MAIN {r[0]}: {val}")

# 也查看 instance_deployments 表
cur.execute("SELECT name FROM sqlite_master WHERE type='table' AND name LIKE '%deploy%'")
tables = [r[0] for r in cur.fetchall()]
print("\nDeploy tables:", tables)

for t in tables:
    cur.execute(f"PRAGMA table_info({t})")
    tcols = [r[1] for r in cur.fetchall()]
    for col in tcols:
        cl = col.lower()
        if 'token' in cl or 'panel' in cl or 'api' in cl or 'auth' in cl:
            cur.execute(f"SELECT id, {col} FROM {t} ORDER BY created_at DESC LIMIT 3")
            for r in cur.fetchall():
                val = str(r[1])[:200] if r[1] else '(null)'
                print(f"  {t}.{col} [{r[0]}]: {val}")

conn.close()
PYEOF

echo ""
echo "=== 尝试通过 Manager panel proxy 注入配置 ==="
# 使用 Manager 的 panel proxy 路径
TUNNEL="fctun_0c91eecdb079d77758df6ffed211e8bae16bb20f1978b23a"
curl -sS -X PUT \
  -H "Content-Type: application/json" \
  -d '{"config":{"api_key":"sk-m2ZMH0W1EYSL4vrXwE0WjvQTSOKhhX4oMp31zZskZ6xDPl96","upstream_base":"http://10.200.0.20:3000","listen_addr":"127.0.0.1:39527"}}' \
  "http://127.0.0.1:19088/panel/friend-4f864178/api/plugins/llm-proxy/config?__friend_tunnel=$TUNNEL" 2>/dev/null
echo ""

echo "等待配置生效..."
sleep 5

echo "=== 通过 panel proxy 检查插件健康 ==="
curl -sS "http://127.0.0.1:19088/panel/friend-4f864178/api/plugins/llm-proxy/health?__friend_tunnel=$TUNNEL" 2>/dev/null
echo ""

echo "=== 通过 panel proxy 检查 LLM overview ==="
curl -sS "http://127.0.0.1:19088/panel/friend-4f864178/api/llm/overview?__friend_tunnel=$TUNNEL" 2>/dev/null
echo ""

echo "=== 通过 panel proxy 测试聊天 ==="
curl -sS -X POST \
  -H "Content-Type: application/json" \
  -d '{"model":"glm-5-2","messages":[{"role":"user","content":"hello"}],"max_tokens":50}' \
  "http://127.0.0.1:19088/panel/friend-4f864178/v1/chat/completions?__friend_tunnel=$TUNNEL" 2>/dev/null | head -c 500
echo ""
