"""
数据库与表管理工具 (工具 7-12)
"""

from ._base import register_tool, ToolDef


@register_tool("list_databases")
class ListDatabasesTool(ToolDef):
    name = "list_databases"
    description = "获取指定数据源下的数据库列表"
    input_schema = {
        "type": "object",
        "properties": {
            "datasourceId": {"type": "string", "description": "数据源 ID"},
            "sourceType": {"type": "string", "enum": ["builtin", "external"], "description": "数据源类型"},
            "pageNum": {"type": "integer", "default": 1, "description": "页码"},
            "pageSize": {"type": "integer", "default": 20, "description": "每页数量"},
        },
        "required": ["datasourceId"],
    }

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


@register_tool("list_tables")
class ListTablesTool(ToolDef):
    name = "list_tables"
    description = "获取指定数据源下的表列表"
    input_schema = {
        "type": "object",
        "properties": {
            "datasourceId": {"type": "string", "description": "数据源 ID"},
            "sourceType": {"type": "string", "enum": ["builtin", "external"], "description": "数据源类型"},
            "pageNum": {"type": "integer", "default": 1, "description": "页码"},
            "pageSize": {"type": "integer", "default": 20, "description": "每页数量"},
        },
        "required": ["datasourceId"],
    }

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


@register_tool("get_table_detail")
class GetTableDetailTool(ToolDef):
    name = "get_table_detail"
    description = "获取表的完整结构信息（字段列表、主键、类型等）"
    input_schema = {
        "type": "object",
        "properties": {
            "tableId": {"type": "string", "description": "表 ID"},
        },
        "required": ["tableId"],
    }

    async def execute(self, args: dict) -> dict:
        table_id = args["tableId"]
        return self.client.get(f"/api/datasource/table/{table_id}/detail")


@register_tool("create_table")
class CreateTableTool(ToolDef):
    name = "create_table"
    description = "在指定数据库创建新表"
    input_schema = {
        "type": "object",
        "properties": {
            "connectionId": {"type": "string", "description": "数据源连接 ID"},
            "databaseName": {"type": "string", "description": "目标数据库名"},
            "tableName": {"type": "string", "description": "表名（小写字母+数字+下划线）"},
            "tableComment": {"type": "string", "description": "表注释"},
            "columns": {
                "type": "array",
                "description": "字段定义数组",
                "items": {
                    "type": "object",
                    "properties": {
                        "columnName": {"type": "string", "description": "字段名"},
                        "columnType": {"type": "string", "description": "字段类型（VARCHAR/INTEGER/SERIAL等）"},
                        "columnLength": {"type": "integer", "description": "字段长度"},
                        "isPrimaryKey": {"type": "boolean", "description": "是否主键"},
                        "isNullable": {"type": "boolean", "description": "是否可空"},
                        "isAutoIncrement": {"type": "boolean", "description": "是否自增"},
                        "columnComment": {"type": "string", "description": "字段注释"},
                        "defaultValue": {"type": "string", "description": "默认值"},
                    },
                    "required": ["columnName", "columnType"],
                },
            },
        },
        "required": ["connectionId", "databaseName", "tableName", "columns"],
    }

    async def execute(self, args: dict) -> dict:
        args = dict(args)
        connection_id = args.pop("connectionId")
        return self.client.post(f"/api/datasource/connection/{connection_id}/create_table", json_data=args)


@register_tool("alter_table")
class AlterTableTool(ToolDef):
    name = "alter_table"
    description = "修改已有表结构（增/改/删字段）"
    input_schema = {
        "type": "object",
        "properties": {
            "connectionId": {"type": "string", "description": "数据源连接 ID"},
            "databaseName": {"type": "string", "description": "数据库名"},
            "tableName": {"type": "string", "description": "表名"},
            "operations": {
                "type": "array",
                "description": "表结构变更操作数组",
                "items": {
                    "type": "object",
                    "properties": {
                        "operation": {"type": "string", "enum": ["ADD_COLUMN", "DROP_COLUMN", "RENAME_COLUMN", "ALTER_COLUMN_TYPE", "SET_NOT_NULL", "DROP_NOT_NULL", "SET_DEFAULT", "DROP_DEFAULT"], "description": "变更类型"},
                        "column": {"type": "object", "description": "列定义（根据 operation 不同包含不同字段）"},
                    },
                    "required": ["operation", "column"],
                },
            },
            "tableComment": {"type": "string", "description": "表注释"},
        },
        "required": ["connectionId", "databaseName", "tableName", "operations"],
    }

    async def execute(self, args: dict) -> dict:
        args = dict(args)
        connection_id = args.pop("connectionId")
        return self.client.put(f"/api/datasource/connection/{connection_id}/alter_table", json_data=args)


@register_tool("generate_table_by_description")
class GenerateTableByDescriptionTool(ToolDef):
    name = "generate_table_by_description"
    description = "通过自然语言描述让 AI 生成表结构（异步任务）"
    input_schema = {
        "type": "object",
        "properties": {
            "requirement": {"type": "string", "description": "业务需求描述"},
            "databaseId": {"type": "integer", "description": "关联的数据库 ID（可选）"},
        },
        "required": ["requirement"],
    }

    async def execute(self, args: dict) -> dict:
        return self.client.post("/api/datasource/connection/generate_table", json_data=args)
