"""
表数据 CRUD 工具 (工具 13-17)
"""

import base64

from ._base import register_tool, ToolDef


@register_tool("query_table_data")
class QueryTableDataTool(ToolDef):
    name = "query_table_data"
    description = "查询内置表数据（分页）。target 默认 test（调试环境）；查询线上数据须显式传 target=prod"
    input_schema = {
        "type": "object",
        "properties": {
            "tableId": {"type": "string", "description": "表 ID"},
            "target": {"type": "string", "enum": ["prod", "test"], "default": "test", "description": "环境，默认 test（调试）；线上数据传 prod"},
            "pageNum": {"type": "integer", "default": 1, "description": "页码"},
            "pageSize": {"type": "integer", "default": 10, "description": "每页数量"},
        },
        "required": ["tableId"],
    }

    async def execute(self, args: dict) -> dict:
        args = dict(args)
        table_id = args.pop("tableId")
        args.setdefault("target", "test")
        params = {k: v for k, v in args.items() if v is not None}
        return await self.client.get(f"/datasource/connection/builtin/table/{table_id}", params=params)


@register_tool("insert_table_row")
class InsertTableRowTool(ToolDef):
    name = "insert_table_row"
    description = "向内置表插入一行数据。⚠️ 写操作 target 默认 test（调试环境）；写入线上库须显式传 target=prod"
    input_schema = {
        "type": "object",
        "properties": {
            "tableId": {"type": "string", "description": "表 ID"},
            "target": {"type": "string", "enum": ["prod", "test"], "default": "test", "description": "⚠️ 环境，默认 test（调试）；写入线上库必须显式传 prod"},
            "data": {"type": "object", "description": "行数据（键值对，键为字段名）"},
        },
        "required": ["tableId", "data"],
    }

    async def execute(self, args: dict) -> dict:
        args = dict(args)
        table_id = args.pop("tableId")
        target = args.pop("target", "test")
        data = args.pop("data", {})
        params = {"target": target} if target else {}
        body = {"data": data}
        return await self.client.post(f"/datasource/connection/builtin/table/{table_id}/rows", json_data=body, params=params)


@register_tool("update_table_row")
class UpdateTableRowTool(ToolDef):
    name = "update_table_row"
    description = "更新内置表的指定行。⚠️ 写操作 target 默认 test（调试环境）；修改线上库须显式传 target=prod"
    input_schema = {
        "type": "object",
        "properties": {
            "tableId": {"type": "string", "description": "表 ID"},
            "target": {"type": "string", "enum": ["prod", "test"], "default": "test", "description": "⚠️ 环境，默认 test（调试）；修改线上库必须显式传 prod"},
            "primaryKey": {"type": "object", "description": "主键值（如 {\"id\": 1}）"},
            "data": {"type": "object", "description": "要更新的字段值"},
        },
        "required": ["tableId", "primaryKey", "data"],
    }

    async def execute(self, args: dict) -> dict:
        args = dict(args)
        table_id = args.pop("tableId")
        target = args.pop("target", "test")
        primary_key = args.pop("primaryKey")
        data = args.pop("data", {})
        params = {"target": target} if target else {}
        body = {"primaryKey": primary_key, "data": data}
        return await self.client.put(f"/datasource/connection/builtin/table/{table_id}/rows", json_data=body, params=params)


@register_tool("delete_table_rows")
class DeleteTableRowsTool(ToolDef):
    name = "delete_table_rows"
    description = "删除内置表的指定行（根据主键批量删除）。⚠️ 写操作 target 默认 test（调试环境）；删除线上库数据须显式传 target=prod"
    input_schema = {
        "type": "object",
        "properties": {
            "tableId": {"type": "string", "description": "表 ID"},
            "target": {"type": "string", "enum": ["prod", "test"], "default": "test", "description": "⚠️ 环境，默认 test（调试）；删除线上库数据必须显式传 prod"},
            "primaryKeys": {
                "type": "array",
                "description": "主键数组（如 [{\"id\": 1}, {\"id\": 2}]）",
                "items": {"type": "object"},
            },
        },
        "required": ["tableId", "primaryKeys"],
    }

    async def execute(self, args: dict) -> dict:
        args = dict(args)
        table_id = args.pop("tableId")
        target = args.pop("target", "test")
        primary_keys = args.pop("primaryKeys")
        params = {"target": target} if target else {}
        body = {"primaryKeys": primary_keys}
        return await self.client.delete(f"/datasource/connection/builtin/table/{table_id}/rows", json_data=body, params=params)


@register_tool("export_table_excel")
class ExportTableExcelTool(ToolDef):
    name = "export_table_excel"
    description = "导出表数据为 Excel 文件（返回 base64 编码）。target 默认 test（调试环境）；导出线上数据须显式传 target=prod"
    input_schema = {
        "type": "object",
        "properties": {
            "tableId": {"type": "string", "description": "表 ID"},
            "target": {"type": "string", "enum": ["prod", "test"], "default": "test", "description": "环境，默认 test（调试）；线上数据传 prod"},
        },
        "required": ["tableId"],
    }

    async def execute(self, args: dict) -> dict:
        args = dict(args)
        table_id = args.pop("tableId")
        target = args.pop("target", "test")
        params = {"target": target} if target else {}
        result = await self.client.get(f"/datasource/connection/builtin/table/{table_id}/export/excel", params=params)
        
        # 处理二进制响应
        if result.get("raw"):
            content = result["data"]
            return {
                "success": True,
                "file_base64": base64.b64encode(content).decode("utf-8"),
                "message": "Excel 文件已导出，请解码 base64 内容获取文件",
            }
        return result
