"""
MQTT 字段关联同步工具（内置源专属，文档 §8）

接口前缀为 /system/mqtt（注意与 /datasource 不同）。

关于 sourceTable / targetTable 的方向（已真机验证）：
直接调后端 API 时按字面透传即可——create 传什么，detail 回显就是什么，
字段自洽、后端不做调换。例：create 传 sourceTable=sys_user/targetTable=users，
detail 读回仍是 sourceTable=sys_user/targetTable=users。
文档 §8 提到的「前端提交时调换」是前端 Vue 组件为 UI 展示所做的转换，
与后端 API 契约无关，本工具（直连 API）无需调换。
"""

from ._base import register_tool, ToolDef


@register_tool("list_mqtt_configs")
class ListMqttConfigsTool(ToolDef):
    name = "list_mqtt_configs"
    description = "获取 MQTT 字段关联同步配置列表"
    input_schema = {
        "type": "object",
        "properties": {
            "pageNum": {"type": "integer", "default": 1, "description": "页码"},
            "pageSize": {"type": "integer", "default": 20, "description": "每页数量"},
        },
        "required": [],
    }

    async def execute(self, args: dict) -> dict:
        params = {k: v for k, v in args.items() if v is not None}
        return await self.client.get("/system/mqtt/config/list", params=params)


@register_tool("get_mqtt_config_detail")
class GetMqttConfigDetailTool(ToolDef):
    name = "get_mqtt_config_detail"
    description = "获取 MQTT 同步配置详情"
    input_schema = {
        "type": "object",
        "properties": {
            "configId": {"type": "string", "description": "配置 ID"},
        },
        "required": ["configId"],
    }

    async def execute(self, args: dict) -> dict:
        return await self.client.get(f"/system/mqtt/config/{args['configId']}")


@register_tool("list_mqtt_target_tables")
class ListMqttTargetTablesTool(ToolDef):
    name = "list_mqtt_target_tables"
    description = "获取 MQTT 可同步的目标表列表"
    input_schema = {"type": "object", "properties": {}, "required": []}

    async def execute(self, args: dict) -> dict:
        return await self.client.get("/system/mqtt/config/tableList")


@register_tool("list_mqtt_target_table_columns")
class ListMqttTargetTableColumnsTool(ToolDef):
    name = "list_mqtt_target_table_columns"
    description = "获取 MQTT 目标表的字段列表"
    input_schema = {
        "type": "object",
        "properties": {
            "tableName": {"type": "string", "description": "目标表名"},
        },
        "required": ["tableName"],
    }

    async def execute(self, args: dict) -> dict:
        return await self.client.get(f"/system/mqtt/config/tableColumns/{args['tableName']}")


@register_tool("create_mqtt_config")
class CreateMqttConfigTool(ToolDef):
    name = "create_mqtt_config"
    description = (
        "新增 MQTT 字段关联同步配置。"
        "sourceTable/targetTable 按字面透传即可（实测确认 create 存入与 detail 回显一致，"
        "无需调换；文档§8 的调换是前端 UI 层行为，与本 API 无关）"
    )
    input_schema = {
        "type": "object",
        "properties": {
            "sourceTable": {"type": "string", "description": "源表名"},
            "targetTable": {"type": "string", "description": "目标表名"},
            "config": {"type": "object", "description": "完整配置体（字段映射等），按后端结构透传"},
        },
        "required": [],
    }

    async def execute(self, args: dict) -> dict:
        # config 若存在则以其为主体，否则直接用 args（去掉 config 包裹键）
        body = args.get("config") if isinstance(args.get("config"), dict) else dict(args)
        return await self.client.post("/system/mqtt/config", json_data=body)


@register_tool("update_mqtt_config")
class UpdateMqttConfigTool(ToolDef):
    name = "update_mqtt_config"
    description = (
        "修改 MQTT 字段关联同步配置。"
        "sourceTable/targetTable 按字面透传即可（实测确认无需调换，详见 create_mqtt_config）"
    )
    input_schema = {
        "type": "object",
        "properties": {
            "id": {"type": "string", "description": "配置 ID"},
            "sourceTable": {"type": "string", "description": "源表名"},
            "targetTable": {"type": "string", "description": "目标表名"},
            "config": {"type": "object", "description": "完整配置体，按后端结构透传"},
        },
        "required": ["id"],
    }

    async def execute(self, args: dict) -> dict:
        if isinstance(args.get("config"), dict):
            body = dict(args["config"])
            body.setdefault("id", args.get("id"))
        else:
            body = dict(args)
        return await self.client.put("/system/mqtt/config", json_data=body)


@register_tool("delete_mqtt_config")
class DeleteMqttConfigTool(ToolDef):
    name = "delete_mqtt_config"
    description = "删除 MQTT 同步配置（支持多个 id，逗号拼接）"
    input_schema = {
        "type": "object",
        "properties": {
            "ids": {"type": "string", "description": "配置 ID，多个用逗号拼接"},
        },
        "required": ["ids"],
    }

    async def execute(self, args: dict) -> dict:
        return await self.client.delete(f"/system/mqtt/config/{args['ids']}")


@register_tool("refresh_mqtt_config_cache")
class RefreshMqttConfigCacheTool(ToolDef):
    name = "refresh_mqtt_config_cache"
    description = "刷新 MQTT 同步配置缓存"
    input_schema = {"type": "object", "properties": {}, "required": []}

    async def execute(self, args: dict) -> dict:
        return await self.client.get("/system/mqtt/config/refreshCache")
