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

echo "=== 安装 llm-proxy 到测试实例 ==="
curl -sS -X POST -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  -d "{\"action\":\"install\",\"artifact_id\":\"$ARTIFACT_ID\"}" \
  "$MANAGER/api/v1/instances/friend-4f864178/extension-actions" 2>/dev/null
echo ""

echo "等待安装完成..."
sleep 20

echo "=== 检查 extensions ==="
curl -sS -H "Authorization: Bearer $TOKEN" \
  "$MANAGER/api/v1/instances/friend-4f864178/extensions" 2>/dev/null
echo ""

echo "=== 检查容器内插件状态 ==="
docker exec friend-deploy-f67b3ed2-e3c sh -c \
  'curl -sS -H "Authorization: Bearer yunwo-panel-2026" http://127.0.0.1:8000/api/plugins 2>/dev/null' \
  | python3 -c "
import json,sys
d=json.load(sys.stdin)
if isinstance(d, list):
    for p in d:
        print(f\"  name={p.get('name','')} status={p.get('status','')} managed={p.get('managed','')}\")
else:
    print(json.dumps(d, indent=2)[:500])
" 2>/dev/null || echo "error"

echo ""
echo "=== 注入插件配置 ==="
docker exec friend-deploy-f67b3ed2-e3c sh -c \
  'curl -sS -X PUT -H "Authorization: Bearer yunwo-panel-2026" -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:8000/api/plugins/llm-proxy/config 2>/dev/null'
echo ""

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

echo "=== 健康检查 ==="
docker exec friend-deploy-f67b3ed2-e3c sh -c \
  'curl -sS -H "Authorization: Bearer yunwo-panel-2026" http://127.0.0.1:8000/api/plugins/llm-proxy/health 2>/dev/null'
echo ""

echo "=== LLM overview ==="
docker exec friend-deploy-f67b3ed2-e3c sh -c \
  'curl -sS -H "Authorization: Bearer yunwo-panel-2026" http://127.0.0.1:8000/api/llm/overview 2>/dev/null'
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('extension_state:', inst.get('extension_state',''))
print('health_state:', inst.get('health_state',''))
print('last_error:', inst.get('last_error','')[:200])
"
