#!/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 "=========================================="
echo "阶段 1: 更新 Config Profile (加入 LLM 配置)"
echo "=========================================="

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": "group/default", "position": 0}]
      }}
    ],
    "issued_by": "admin"
  }' \
  "$MANAGER/api/v1/config-profiles/$PROFILE_ID" 2>/dev/null

echo ""
echo ""

echo "=========================================="
echo "阶段 2: 创建实例部署"
echo "=========================================="

DEPLOY_RESPONSE=$(curl -sS -X POST -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  -d '{
    "name": "yunwo-test-instance",
    "cluster_id": "'"$CLUSTER_ID"'",
    "provisioning_mode": "automatic",
    "desired_run_state": "running",
    "friend_version": "0.1.0",
    "server_pool_id": "pool-e1d4ad76-8",
    "network_domain_id": "net-a835fff0-b",
    "image": "friend-cluster-friend-node:real",
    "resources": {
      "cpu_cores": 1,
      "memory_bytes": 1073741824,
      "disk_bytes": 5368709120
    },
    "labels": {
      "yunwo.ai/agent-id": "test-001",
      "yunwo.ai/agent-type": "test-agent",
      "yunwo.ai/tenant": "yunwo"
    },
    "issued_by": "admin"
  }' \
  "$MANAGER/api/v1/instance-deployments" 2>/dev/null)

echo "$DEPLOY_RESPONSE" | python3 -c "
import json,sys
d=json.load(sys.stdin)
print('deployment_id:', d.get('id',''))
print('instance_id:', d.get('instance_id',''))
print('status:', d.get('status',''))
print('enrollment_token:', d.get('enrollment_token','')[:20]+'...' if d.get('enrollment_token','') else '(hidden)')
print('last_error:', d.get('last_error','')[:200])
"

echo ""
echo "等待实例就绪..."
sleep 30

echo "=========================================="
echo "阶段 3: 检查实例状态"
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','')}\")
"

echo ""
echo "=========================================="
echo "阶段 4: 检查现有实例配置收敛状态"
echo "=========================================="

# 检查现有实例是否继承了新 LLM 配置
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)
conn.close()
PYEOF
