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

echo "=== 检查 config-transaction 状态 ==="
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('generation:', d.get('generation',''))
print('applied_generation:', d.get('applied_generation',''))
items = d.get('items', d.get('resources', []))
for item in items:
    kind = item.get('kind','')
    if 'plugin' in kind.lower():
        print(f'  PLUGIN CONFIG: {json.dumps(item)[:300]}')
"

echo ""
echo "=== 检查实例状态 ==="
curl -sS -H "Authorization: Bearer $TOKEN" \
  "$MANAGER/api/v1/instances/friend-4f864178" 2>/dev/null | python3 -c "
import json,sys
d=json.load(sys.stdin)
inst=d.get('instance',d)
print('config_state:', inst.get('config_state',''))
print('desired_config_generation:', inst.get('desired_config_generation',''))
print('applied_config_generation:', inst.get('applied_config_generation',''))
print('extension_state:', inst.get('extension_state',''))
print('health_state:', inst.get('health_state',''))
print('last_error:', inst.get('last_error','')[:300])
"

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

# 查看 config_transactions 表
cur.execute("PRAGMA table_info(config_transactions)")
cols = [r[1] for r in cur.fetchall()]
print("config_transactions columns:", cols)

# 查看测试实例最近的 config_transactions
cur.execute("SELECT * FROM config_transactions WHERE instance_id='friend-4f864178' ORDER BY created_at DESC LIMIT 3")
for r in cur.fetchall():
    print(f"  TX: id={r[0]} status={r[3] if len(r)>3 else '?'} base_gen={r[4] if len(r)>4 else '?'} target_gen={r[5] if len(r)>5 else '?'}")

# 查看 config_resources 表结构
cur.execute("PRAGMA table_info(config_resources)")
cols = [r[1] for r in cur.fetchall()]
print("\nconfig_resources columns:", cols)

# 查看测试实例的 config_resources
cur.execute("SELECT * FROM config_resources WHERE instance_id='friend-4f864178'")
for r in cur.fetchall():
    # Print all columns
    print(f"  RES: {r}")

# 查看主实例的 config_resources 中 plugin.config
cur.execute("SELECT * FROM config_resources WHERE instance_id='friend-043bd076'")
for r in cur.fetchall():
    print(f"  MAIN RES: {str(r)[:300]}")

# 搜索所有表中的 secret/token
cur.execute("SELECT name FROM sqlite_master WHERE type='table'")
all_tables = [r[0] for r in cur.fetchall()]
for t in all_tables:
    cur.execute(f"PRAGMA table_info({t})")
    tcols = [c[1] for c in cur.fetchall()]
    for col in tcols:
        cl = col.lower()
        if 'secret' in cl or 'api_auth' in cl or 'panel_token' in cl:
            print(f"\n  TABLE {t} has column {col}")
            try:
                cur.execute(f"SELECT id, {col} FROM {t} LIMIT 3")
                for r in cur.fetchall():
                    print(f"    {t}.{col} [{r[0]}]: {str(r[1])[:100]}")
            except:
                pass

conn.close()
PYEOF

echo ""
echo "=== 通过 config-transactions 推送 plugin.config (获取当前 generation) ==="
# 先获取当前 generation
GEN=$(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(d.get('generation', d.get('desired_generation', 0)))
" 2>/dev/null)
echo "Current generation: $GEN"

# 推送 plugin.config
curl -sS -X POST -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  -d "{
    \"base_generation\": $GEN,
    \"changes\": [
      {
        \"kind\": \"plugin.config\",
        \"operation\": \"set\",
        \"resource_uid\": \"llm-proxy\",
        \"value\": {
          \"api_key\": \"sk-m2ZMH0W1EYSL4vrXwE0WjvQTSOKhhX4oMp31zZskZ6xDPl96\",
          \"listen_addr\": \"127.0.0.1:39527\",
          \"upstream_base\": \"http://10.200.0.20:3000\"
        }
      }
    ]
  }" \
  "$MANAGER/api/v1/instances/friend-4f864178/config-transactions" 2>/dev/null
echo ""

echo "等待配置收敛..."
sleep 15

echo "=== 再次检查实例状态 ==="
curl -sS -H "Authorization: Bearer $TOKEN" \
  "$MANAGER/api/v1/instances/friend-4f864178" 2>/dev/null | python3 -c "
import json,sys
d=json.load(sys.stdin)
inst=d.get('instance',d)
print('config_state:', inst.get('config_state',''))
print('desired_config_generation:', inst.get('desired_config_generation',''))
print('applied_config_generation:', inst.get('applied_config_generation',''))
print('last_error:', inst.get('last_error','')[:300])
"

echo ""
echo "=== 检查容器内插件健康 ==="
docker exec friend-deploy-f67b3ed2-e3c sh -c \
  'curl -sS http://127.0.0.1:8000/api/plugins/llm-proxy/health 2>/dev/null' || echo "no auth"
echo ""

echo "=== 尝试通过 extension-set 推送 plugin config ==="
curl -sS -X PUT -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  -d '{
    "base_generation": 0,
    "items": [
      {
        "kind": "plugin",
        "id": "llm-proxy",
        "version": "0.1.0",
        "artifact_id": "artifact-f0ae75f6-1",
        "desired": "present",
        "enabled": true,
        "config": {
          "api_key": "sk-m2ZMH0W1EYSL4vrXwE0WjvQTSOKhhX4oMp31zZskZ6xDPl96",
          "listen_addr": "127.0.0.1:39527",
          "upstream_base": "http://10.200.0.20:3000"
        }
      }
    ]
  }' \
  "$MANAGER/api/v1/instances/friend-4f864178/extension-set" 2>/dev/null
echo ""

echo "等待 extension 收敛..."
sleep 10

echo "=== 最终检查 ==="
curl -sS -H "Authorization: Bearer $TOKEN" \
  "$MANAGER/api/v1/instances/friend-4f864178/extensions" 2>/dev/null
echo ""
curl -sS -H "Authorization: Bearer $TOKEN" \
  "$MANAGER/api/v1/instances/friend-4f864178" 2>/dev/null | python3 -c "
import json,sys
d=json.load(sys.stdin)
inst=d.get('instance',d)
print('config_state:', inst.get('config_state',''))
print('extension_state:', inst.get('extension_state',''))
print('health_state:', inst.get('health_state',''))
print('last_error:', inst.get('last_error','')[:300])
"
