# -*- coding: utf-8 -*-
"""
Schema 生成工具模块。
"""

from copy import deepcopy
from typing import Any, Dict


def _normalize_schema(parameters: Dict[str, Any] | None) -> Dict[str, Any]:
    """将任意参数定义归一化为 object schema。"""
    if not isinstance(parameters, dict) or not parameters:
        return {
            "type": "object",
            "properties": {},
            "required": []
        }

    input_schema = deepcopy(parameters)
    input_schema["type"] = "object"

    if not isinstance(input_schema.get("properties"), dict):
        input_schema["properties"] = {}

    if not isinstance(input_schema.get("required"), list):
        input_schema["required"] = []

    return input_schema


def generate_input_schema(parameters: Dict[str, Any] | None) -> Dict[str, Any]:
    """
    从查询配置的参数定义生成 MCP 工具的 inputSchema。

    会统一补齐：
    - `targetDatabaseName`：可选
    - `userId`：必填
    """
    input_schema = _normalize_schema(parameters)

    if "targetDatabaseName" not in input_schema["properties"]:
        input_schema["properties"]["targetDatabaseName"] = {
            "type": "string",
            "description": "目标数据库名称",
            "default": ""
        }

    if "userId" not in input_schema["properties"]:
        input_schema["properties"]["userId"] = {
            "type": "string",
            "description": "当前 AI 平台用户 ID"
        }

    if "userId" not in input_schema["required"]:
        input_schema["required"].append("userId")

    return input_schema


def validate_input_schema(schema: Dict[str, Any]) -> tuple[bool, str]:
    """
    验证 inputSchema 是否符合基本的 JSON Schema 规范。
    """
    if not isinstance(schema, dict):
        return False, "Schema 必须是一个字典对象"

    if schema.get("type") != "object":
        return False, "Schema 的 type 字段必须是 'object'"

    if "properties" not in schema:
        return False, "Schema 必须包含 properties 字段"

    if not isinstance(schema.get("properties"), dict):
        return False, "Schema 的 properties 字段必须是一个字典对象"

    if "required" in schema:
        required = schema["required"]
        if not isinstance(required, list):
            return False, "Schema 的 required 字段必须是一个列表"

        properties = schema["properties"]
        for field in required:
            if field not in properties:
                return False, f"必填字段 '{field}' 未在 properties 中定义"

    for prop_name, prop_def in schema["properties"].items():
        if not isinstance(prop_def, dict):
            return False, f"属性 '{prop_name}' 的定义必须是一个字典对象"

        if "type" not in prop_def:
            return False, f"属性 '{prop_name}' 必须包含 type 字段"

    return True, "Schema 验证通过"
