"""配置管理工具"""

import json
from typing import Any

from mcp.types import Tool, TextContent

from trailbase_mcp.client.client import TrailBaseClient


def get_config_tools() -> list[Tool]:
    """获取配置相关工具"""
    return [
        Tool(
            name="config.get",
            description="获取配置",
            inputSchema={
                "type": "object",
                "properties": {},
            },
        ),
        Tool(
            name="config.update",
            description="更新配置",
            inputSchema={
                "type": "object",
                "properties": {
                    "patch": {
                        "type": "object",
                        "description": "配置补丁（server, auth, email, storage, system_jobs, record_apis）",
                    },
                },
                "required": ["patch"],
            },
        ),
    ]


async def handle_config_get(
    client: TrailBaseClient,
) -> list[TextContent]:
    """处理 config.get 工具调用"""
    try:
        result = client.http.get("/api/_admin/config")
        return [TextContent(type="text", text=json.dumps(result, ensure_ascii=False))]
    except Exception as e:
        return [TextContent(type="text", text=json.dumps({"error": str(e)}, ensure_ascii=False))]


async def handle_config_update(
    client: TrailBaseClient,
    patch: dict[str, Any],
) -> list[TextContent]:
    """处理 config.update 工具调用"""
    try:
        # 只允许更新特定字段
        allowed_keys = {"server", "auth", "email", "storage", "system_jobs", "record_apis"}
        filtered_patch = {k: v for k, v in patch.items() if k in allowed_keys}
        
        if not filtered_patch:
            return [TextContent(
                type="text",
                text=json.dumps({
                    "error": "No valid fields to update",
                    "message": f"配置补丁中没有有效的字段。允许的字段: {sorted(allowed_keys)}",
                    "provided_keys": list(patch.keys()),
                }, ensure_ascii=False)
            )]

        # TrailBase 配置 API 使用 protobuf 格式，但目前 SDK 可能不支持
        # 返回提示信息，建议使用 TrailBase CLI 或直接编辑配置文件
        return [TextContent(
            type="text",
            text=json.dumps({
                "error": "NotImplemented",
                "message": "配置更新需要使用 protobuf 格式，当前 MCP 实现暂不支持。",
                "suggestion": "请使用 TrailBase CLI 命令或直接编辑配置文件来更新配置",
                "cli_command": "trail config update",
                "config_file": "traildepot/config.textproto",
                "requested_patch": filtered_patch,
                "note": "如果需要支持配置更新，需要实现完整的 protobuf 编码/解码功能",
            }, ensure_ascii=False)
        )]
    except Exception as e:
        # 提取详细的错误信息
        error_info: dict[str, Any] = {"error": str(e), "error_type": type(e).__name__}
        
        # 如果是 TrailBaseHTTPError，提取更多信息
        from trailbase_mcp.client.errors import TrailBaseHTTPError
        if isinstance(e, TrailBaseHTTPError):
            error_info.update({
                "status_code": e.status_code,
                "code": e.code,
                "message": e.message,
                "details": e.details,
            })
        
        # 添加请求信息用于调试
        error_info["request_patch"] = patch
        error_info["filtered_patch"] = {k: v for k, v in patch.items() if k in {"server", "auth", "email", "storage", "system_jobs", "record_apis"}}
        
        return [TextContent(type="text", text=json.dumps(error_info, ensure_ascii=False))]

