"""
SQL 执行工具 (工具 33)
"""

from ._base import register_tool, ToolDef


@register_tool("execute_sql")
class ExecuteSqlTool(ToolDef):
    name = "execute_sql"
    description = "执行原生 SQL 查询"
    input_schema = {
        "type": "object",
        "properties": {
            "datasourceId": {"type": "string", "description": "数据源 ID"},
            "sql": {"type": "string", "description": "SQL 语句"},
            "target": {"type": "string", "enum": ["prod", "test"], "default": "prod", "description": "环境，默认 prod"},
            "sqlTemplate": {"type": "string", "description": "SQL 模板（可选）"},
            "businessName": {"type": "string", "description": "业务名称（可选）"},
            "params": {"type": "object", "description": "SQL 参数对象（可选）"},
        },
        "required": ["datasourceId", "sql"],
    }

    async def execute(self, args: dict) -> dict:
        # 映射参数名为后端 API 期望的格式
        body = {}
        if "datasourceId" in args:
            body["datasourceId"] = args["datasourceId"]
        if "sql" in args:
            body["executableSql"] = args["sql"]
        if "sqlTemplate" in args:
            body["sqlTemplate"] = args["sqlTemplate"]
        if "businessName" in args:
            body["businessName"] = args["businessName"]
        if "params" in args:
            body["parameters"] = args["params"]
        # target 通过 query 参数下发（prod/test 双环境），默认 prod
        target = args.get("target", "prod")
        params = {"target": target} if target else None
        return await self.client.post(
            "/datasource/sqlExecutionLog/testSqlWithSchema",
            json_data=body,
            params=params,
        )
