"""
表订阅工具 (工具 32)
"""

from ._base import register_tool, ToolDef


@register_tool("toggle_table_subscription")
class ToggleTableSubscriptionTool(ToolDef):
    name = "toggle_table_subscription"
    description = "切换表的订阅状态（订阅依赖该表已配置 MQTT 字段关联，否则后端会报操作失败）"
    input_schema = {
        "type": "object",
        "properties": {
            "configId": {"type": "string", "description": "库/配置 ID（即 list_databases 返回的 config id）"},
            "tableName": {"type": "string", "description": "表名（注意：后端按表名而非 tableId 识别）"},
            "subscribe": {"type": "boolean", "description": "true=订阅, false=取消订阅"},
        },
        "required": ["configId", "tableName", "subscribe"],
    }

    async def execute(self, args: dict) -> dict:
        # 后端真实字段（已真机探测确认）：configId + tableName + isSubscribe(bool)
        # 兼容旧参数名 datasourceId->configId
        config_id = args.get("configId") or args.get("datasourceId")
        body = {
            "configId": config_id,
            "tableName": args.get("tableName"),
            "isSubscribe": args.get("subscribe"),
        }
        return await self.client.post("/datasource/subscription/toggle", json_data=body)
