#!/bin/bash
set -e

MANAGER="http://127.0.0.1:19088"
TOKEN="dev-admin-token"
CLUSTER_ID="yunwocloud-4af3c7"
PROFILE_ID="profile-c92edf65-a"

echo "=== 更新 config profile (修复 route candidate target_type) ==="
curl -sS -X PUT -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  -d '{
    "name": "YunWo Brain State",
    "cluster_id": "'"$CLUSTER_ID"'",
    "priority": 0,
    "resources": [
      {"kind": "runtime.key", "key": "brain.enabled", "value": true},
      {"kind": "runtime.key", "key": "brain.context_window_size", "value": 131072},
      {"kind": "llm.channel", "resource_uid": "channel/llm-proxy", "value": {
        "name": "llm-proxy",
        "protocol": "openai",
        "api_base": "http://127.0.0.1:39527/v1",
        "credential_configured": true
      }},
      {"kind": "llm.model", "resource_uid": "model/llm-proxy/glm-5-2", "value": {
        "model_key": "glm-5-2",
        "enabled": true,
        "supports_tools": false
      }},
      {"kind": "llm.group", "resource_uid": "group/default", "value": {
        "name": "Default",
        "members": ["channel/llm-proxy"]
      }},
      {"kind": "llm.route", "resource_uid": "route/brain-thinking", "value": {
        "purpose": "brain_thinking",
        "candidates": [{"target_type": "group", "target": "group/default", "position": 0}]
      }}
    ],
    "issued_by": "admin"
  }' \
  "$MANAGER/api/v1/config-profiles/$PROFILE_ID" 2>/dev/null | python3 -c "
import json,sys
d=json.load(sys.stdin)
print('revision:', d.get('revision',''))
print('error:', d.get('error',''))
"

echo ""
echo "等待 config 收敛..."
sleep 20

echo "=== 检查实例状态 ==="
curl -sS -H "Authorization: Bearer $TOKEN" "$MANAGER/api/v1/instances/friend-043bd076" 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','')[:200])
"

echo ""
echo "=== 检查 config_resources ==="
python3 << 'PYEOF'
import sqlite3
conn = sqlite3.connect("/opt/friend-cluster/data/friend-cluster-v1.db")
cur = conn.cursor()
cur.execute("SELECT instance_id,kind,resource_key,value_json,source FROM config_resources WHERE instance_id=?", ("friend-043bd076",))
for r in cur.fetchall(): print("CFG:", r[1], r[2], r[3][:100], r[4])
conn.close()
PYEOF

echo ""
echo "=== 检查新实例状态 ==="
curl -sS -H "Authorization: Bearer $TOKEN" "$MANAGER/api/v1/instances" 2>/dev/null | python3 -c "
import json,sys
d=json.load(sys.stdin)
for x in d:
    print(f\"  {x.get('id','')} | {x.get('name','')} | state={x.get('process_state','')} | health={x.get('health_state','')} | config={x.get('config_state','')}\")
"
