#!/bin/bash
# M3 v6：为 friend-48beca9b 下发 llm-proxy 插件配置并重启插件
BASE=http://10.168.3.36:19088
INST=friend-48beca9b
AUTH="Authorization: Bearer dev-admin-token"
CT="Content-Type: application/json"

echo "=== 1. 查现有 config-profile / 实例当前配置里的 plugin.config ==="
curl -sS -H "$AUTH" "$BASE/api/v1/config-profiles" | python3 -c "
import sys,json
for p in (json.load(sys.stdin) if isinstance(json.load(open('/dev/null')) if False else json.loads(sys.stdin.read() or '[]'), list) else []):
    print(p.get('id'), '|', p.get('name'))" 2>/dev/null || true

echo "=== 2. 通过 config-transactions 下发 llm-proxy 插件配置 ==="
PAYLOAD=$(cat <<EOF
{
  "operations": [
    {
      "operation": "set",
      "resource": {"kind":"plugin.config","resource_uid":"llm-proxy","value":{
        "api_key":"sk-yunwo-internal",
        "upstream_base":"http://10.200.0.20:3000",
        "listen_addr":"127.0.0.1:39527"
      }}
    }
  ]
}
EOF
)
RESP=$(curl -sS --max-time 15 -X POST -H "$AUTH" -H "$CT" -d "$PAYLOAD" "$BASE/api/v1/instances/$INST/config-transactions")
echo "$RESP" | head -c 400; echo

echo "=== 3. 等 8s 后查 extensions 状态 ==="
sleep 8
curl -sS -H "$AUTH" "$BASE/api/v1/instances/$INST/extensions" | python3 -c "
import sys,json
for e in json.load(sys.stdin):
    print(e.get('id'),'|',e.get('state'),'|',json.dumps(e.get('config',{}))[:120])"

echo "=== 4. 若仍 failed 则重发 install 命令 ==="
STATE=$(curl -sS -H "$AUTH" "$BASE/api/v1/instances/$INST/extensions" | python3 -c "import sys,json; print(json.load(sys.stdin)[0].get('state',''))")
if [ "$STATE" = "failed" ]; then
  echo "--- 重发 install ---"
  curl -sS --max-time 15 -X POST -H "$AUTH" -H "$CT" -d '{"action":"install","artifact_id":"artifact-f0ae75f6-1"}' "$BASE/api/v1/instances/$INST/extension-actions" | head -c 200; echo
  sleep 15
  curl -sS -H "$AUTH" "$BASE/api/v1/instances/$INST/extensions" | python3 -c "
import sys,json
for e in json.load(sys.stdin):
    print(e.get('id'),'|',e.get('state'),'|',json.dumps(e.get('config',{}))[:150])"
fi

echo "=== 5. 验证 39527 监听 + LLM 健康 ==="
C=friend-deploy-0acc642d-5c1
docker exec $C sh -c 'cat /proc/net/tcp /proc/net/tcp6 2>/dev/null' | awk 'NR>1 {split($2,a,":"); p=strtonum("0x" a[2]); if (p==39527) print "39527_LISTENING"}'
ITOK=$(docker exec $C sh -c "grep api_auth_token /app/config/config.yaml" | awk '{print $2}')
TTOK=$(curl -sS --max-time 10 -X POST -H "$AUTH" -H "$CT" -d '{}' "$BASE/api/v1/instances/$INST/tunnels" | python3 -c "
import sys,json,urllib.parse as u
print(u.parse_qs(u.urlparse(json.load(sys.stdin)['url']).query)['__friend_tunnel'][0])")
curl -sS --max-time 15 -H "Cookie: friend_cluster_tunnel=$TTOK" -H "Authorization: Bearer $ITOK" "$BASE/panel/$INST/api/llm/models" | python3 -c "
import sys,json
try:
    for m in json.load(sys.stdin):
        r=m.get('runtime') or {}
        print(m.get('model_key'),'|',r.get('state'),'|',(r.get('last_error') or '')[:80])
except Exception as ex: print('parse_err',ex)"
echo DONE
