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

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

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

for col in cols:
    if 'token' in col.lower() or 'panel' in col.lower() or 'api' in col.lower() or 'auth' in col.lower():
        cur.execute(f"SELECT id, {col} FROM friend_instances WHERE id='friend-4f864178'")
        for r in cur.fetchall():
            print(f"  TEST {col}: {r[1]}")
        cur.execute(f"SELECT id, {col} FROM friend_instances WHERE id='friend-043bd076'")
        for r in cur.fetchall():
            print(f"  MAIN {col}: {r[1]}")

conn.close()
PYEOF

echo ""
echo "=== 查看测试实例 config ==="
curl -sS -H "Authorization: Bearer $TOKEN" \
  "$MANAGER/api/v1/instances/friend-4f864178/config" 2>/dev/null | python3 -c "
import json,sys
d=json.load(sys.stdin)
print(json.dumps(d, indent=2)[:1000])
"

echo ""
echo "=== 尝试无认证访问插件 ==="
docker exec friend-deploy-f67b3ed2-e3c sh -c \
  'curl -sS http://127.0.0.1:8000/api/plugins 2>/dev/null' | head -c 500
echo ""

echo ""
echo "=== 查看 friend_config 表 ==="
python3 << 'PYEOF'
import sqlite3
conn = sqlite3.connect("/opt/friend-cluster/data/friend-cluster-v1.db")
cur = conn.cursor()
# Check if there's a friend_config table with panel tokens
cur.execute("SELECT name FROM sqlite_master WHERE type='table' AND name LIKE '%config%'")
tables = [r[0] for r in cur.fetchall()]
print("Config tables:", tables)

# Check config_resources for test instance
cur.execute("SELECT kind, resource_uid, value FROM config_resources WHERE instance_id='friend-4f864178' LIMIT 10")
for r in cur.fetchall():
    print(f"  CFG: {r[0]} {r[1]} = {str(r[2])[:200]}")

# Check config_resources for main instance
cur.execute("SELECT kind, resource_uid, value FROM config_resources WHERE instance_id='friend-043bd076' LIMIT 10")
for r in cur.fetchall():
    print(f"  MAIN CFG: {r[0]} {r[1]} = {str(r[2])[:200]}")

conn.close()
PYEOF

echo ""
echo "=== 尝试 panel tunnel ==="
curl -sS -X POST -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  -d '{}' "$MANAGER/api/v1/instances/friend-4f864178/tunnels" 2>/dev/null
echo ""
