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

echo "=== 通过 config-transactions 推送 plugin.config ==="
curl -sS -X POST -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  -d '{
    "changes": [
      {
        "kind": "plugin.config",
        "operation": "set",
        "resource_uid": "llm-proxy",
        "value": {
          "api_key": "sk-m2ZMH0W1EYSL4vrXwE0WjvQTSOKhhX4oMp31zZskZ6xDPl96",
          "upstream_base": "http://10.200.0.20:3000",
          "listen_addr": "127.0.0.1:39527"
        }
      }
    ]
  }' "$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('extension_state:', inst.get('extension_state',''))
print('health_state:', inst.get('health_state',''))
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:39527/health 2>/dev/null' || echo "health check failed"
echo ""

echo "=== 检查容器内 LLM overview ==="
docker exec friend-deploy-f67b3ed2-e3c sh -c \
  'curl -sS http://127.0.0.1:8000/api/llm/overview 2>/dev/null' | python3 -c "
import json,sys
d=json.load(sys.stdin)
print(json.dumps(d, indent=2))
" 2>/dev/null || echo "LLM overview failed"

echo ""
echo "=== 检查容器内 LLM channels ==="
docker exec friend-deploy-f67b3ed2-e3c sh -c \
  'curl -sS http://127.0.0.1:8000/api/llm/channels 2>/dev/null' | python3 -c "
import json,sys
d=json.load(sys.stdin)
if isinstance(d, list):
    for c in d:
        print(f'  id={c.get(\"id\",\"\")} name={c.get(\"name\",\"\")} status={c.get(\"status\",\"\")} api_base={c.get(\"api_base\",\"\")}')
else:
    print(json.dumps(d, indent=2)[:500])
" 2>/dev/null || echo "channels failed"
