"""
OpenClaw 配置更新脚本

向 openclaw.json 中追加 training-admin、training-qa 以及 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("training-qa", {})
    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": "training-admin",
        "workspace": "/home/node/.openclaw/workspace-training",
        "identity": {
            "name": admin_name,
            "theme": admin_name,
            "emoji": "🤖"
        },
        "subagents": {
            "allowAgents": ["training-qa"]
        }
    }
    qa_agent_config = {
        "id": "training-qa",
        "workspace": "/home/node/.openclaw/workspace-training/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": "training-qa",
        "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 == "training-admin":
            raise ValueError("培训管理员 agent 已存在")
        elif aid == "training-qa":
            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["training-qa"] = qa_agent_account_config
        bot_api_channel_config["accounts"] = accounts_config
    else:
        bot_api_channel_config = {
            "accounts": {
                "training-qa": 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()
