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

echo "=== 通过 config-transactions 推送 plugin.config (base_generation=3) ==="
curl -sS -X POST -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  -d '{
    "base_generation": 3,
    "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('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 "=== 检查插件健康 ==="
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 "=== 通过 panel tunnel 注入配置 ==="
TUNNEL_URL="http://friend-4f864178.100.122.74.120.nip.io:19088"
TUNNEL_TOKEN="fctun_2439552814ff305e131cb8fa945043fd3d0437b213592277"
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"}}' \
  "$TUNNEL_URL/api/plugins/llm-proxy/config?__friend_tunnel=$TUNNEL_TOKEN" 2>/dev/null
echo ""

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

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 "=== Chat test ==="
docker exec friend-deploy-f67b3ed2-e3c sh -c \
  '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:39527/v1/chat/completions 2>/dev/null' | head -c 500
echo ""
