"""
OpenClaw 配置更新脚本

向 openclaw.json 中追加 knowledge-admin、qa-agent 以及 main 三个 agent 的配置。
"""

import argparse
import json
import os
import secrets
import sys

def get_api_secret(config_path: str = "/home/node/.openclaw/openclaw.json"):
    if not os.path.exists(config_path):
        raise FileNotFoundError(f"Config file not found: {config_path}")
    try:
        with open(config_path, "r", encoding="utf-8") as f:
            config = json.load(f)
    except json.JSONDecodeError:
        raise ValueError(f"Invalid JSON in config file: {config_path}")
    channels = config.get("channels", {})
    bot_api_channel_config = channels.get("bot-api", {})
    if not bot_api_channel_config:
        return None
    accounts_config = bot_api_channel_config.get("accounts", {})
    if not accounts_config:
        return None
    qa_agent_config = accounts_config.get("qa-agent", {})
    if not qa_agent_config:
        return None
    return qa_agent_config.get("apiSecret", None)


def update_config(admin_name: str, qa_name: str, config_path: str = "/home/node/.openclaw/openclaw.json"):
    if not os.path.exists(config_path):
        raise FileNotFoundError(f"Config file not found: {config_path}")

    with open(config_path, "r", encoding="utf-8") as f:
        config = json.load(f)

    admin_agent_config = {
        "id": "knowledge-admin",
        "workspace": "/home/node/.openclaw/workspace-knowledge",
        "identity": {
            "name": admin_name,
            "theme": admin_name,
            "emoji": "🤖"
        },
        "subagents": {
            "allowAgents": ["qa-agent"]
        }
    }
    qa_agent_config = {
        "id": "qa-agent",
        "workspace": "/home/node/.openclaw/workspace-knowledge/workspace-qa",
        "identity": {
            "name": qa_name,
            "theme": qa_name,
            "emoji": "💁"
        },
        "tools": {
            "deny": ["exec", "web_search", "web_fetch"]
        }
    }
    main_agent_config = {
        "id": "main",
        "workspace": "/home/node/.openclaw/workspace",
        "identity": {
            "name": "main",
            "theme": "main",
            "emoji": "🦞"
        }
    }

    qa_agent_account_config = {
        "agentId": "qa-agent",
        "name": qa_name,
        "apiSecret": secrets.token_hex(32),
        "enabled": True
    }
    config.setdefault("agents", {})
    agents = config.get("agents", {}).get("list", [])
    has_main = False
    for agent in agents:
        aid = agent.get("id") if isinstance(agent, dict) else None
        if aid == "main":
            has_main = True
        elif aid == "knowledge-admin":
            raise ValueError("知识管理员 agent 已存在")
        elif aid == "qa-agent":
            raise ValueError("客服助手 agent 已存在")

    if not has_main:
        agents.append(main_agent_config)
    agents.append(admin_agent_config)
    agents.append(qa_agent_config)
    config["agents"]["list"] = agents

    # 启用 bot-api 插件（用 setdefault 保证 plugins.entries 与 bot-api 存在，避免 KeyError）
    plugins = config.get("plugins", {})
    entries = plugins.setdefault("entries", {})
    entries.setdefault("bot-api", {})["enabled"] = True
    config["plugins"] = plugins

    # 添加客服子系统的channel配置
    channels = config.get("channels", {})
    bot_api_channel_config = channels.get("bot-api", {})
    if bot_api_channel_config:
        accounts_config = bot_api_channel_config.get("accounts", {})
        accounts_config["qa-agent"] = qa_agent_account_config
        bot_api_channel_config["accounts"] = accounts_config
    else:
        bot_api_channel_config = {
            "accounts": {
                "qa-agent": qa_agent_account_config
            }
        }
    channels["bot-api"] = bot_api_channel_config
    config["channels"] = channels

    with open(config_path, "w", encoding="utf-8") as f:
        json.dump(config, f, indent=4, ensure_ascii=False)
    return True


def main():
    parser = argparse.ArgumentParser(description="向 openclaw.json 注入客服 agent 配置")
    parser.add_argument("--admin-name", default="客服管理员", help="知识管理员显示名称")
    parser.add_argument("--qa-name", default="客服助手", help="客服助手显示名称")
    parser.add_argument("--config", default="/home/node/.openclaw/openclaw.json", help="openclaw.json 路径")
    args = parser.parse_args()
    try:
        update_config(args.admin_name, args.qa_name, args.config)
        print(f"✅ 配置更新成功：管理员={args.admin_name}, 客服={args.qa_name}")
        print(f"客服助手 API Secret: {get_api_secret(args.config)}")
    except Exception as e:
        print(f"❌ 配置更新失败：{e}")
        sys.exit(1)


if __name__ == "__main__":
    main()
