"""
API 密钥管理工具（含创建、状态切换、删除、权限查询/授予/撤销）
"""

from ._base import register_tool, ToolDef


@register_tool("list_api_keys")
class ListApiKeysTool(ToolDef):
    name = "list_api_keys"
    description = "获取 API 密钥列表"
    input_schema = {
        "type": "object",
        "properties": {
            "apiKeyName": {"type": "string", "description": "密钥名称模糊搜索"},
            "pageNum": {"type": "integer", "default": 1, "description": "页码"},
            "pageSize": {"type": "integer", "default": 20, "description": "每页数量"},
        },
        "required": [],
    }

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


@register_tool("create_api_key")
class CreateApiKeyTool(ToolDef):
    name = "create_api_key"
    description = "创建新的 API 密钥"
    input_schema = {
        "type": "object",
        "properties": {
            "apiKeyName": {"type": "string", "description": "密钥名称（最多50字）"},
        },
        "required": ["apiKeyName"],
    }

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


@register_tool("toggle_api_key_status")
class ToggleApiKeyStatusTool(ToolDef):
    name = "toggle_api_key_status"
    description = "启用/禁用 API 密钥"
    input_schema = {
        "type": "object",
        "properties": {
            "id": {"type": "string", "description": "密钥 ID"},
            "status": {"type": "integer", "enum": [0, 1], "description": "0=启用, 1=禁用"},
        },
        "required": ["id", "status"],
    }

    async def execute(self, args: dict) -> dict:
        return await self.client.put("/datasource/api_key", json_data=args)


@register_tool("delete_api_key")
class DeleteApiKeyTool(ToolDef):
    name = "delete_api_key"
    description = "删除 API 密钥"
    input_schema = {
        "type": "object",
        "properties": {
            "id": {"type": "string", "description": "密钥 ID"},
        },
        "required": ["id"],
    }

    async def execute(self, args: dict) -> dict:
        return await self.client.delete(f"/datasource/api_key/{args['id']}")


@register_tool("get_api_key_permissions")
class GetApiKeyPermissionsTool(ToolDef):
    name = "get_api_key_permissions"
    description = "查看指定密钥的权限配置"
    input_schema = {
        "type": "object",
        "properties": {
            "apiKeyId": {"type": "string", "description": "密钥 ID"},
        },
        "required": ["apiKeyId"],
    }

    async def execute(self, args: dict) -> dict:
        return await self.client.get(f"/datasource/api_key/permission/{args['apiKeyId']}")


@register_tool("grant_api_key_permissions")
class GrantApiKeyPermissionsTool(ToolDef):
    name = "grant_api_key_permissions"
    description = "批量为 API 密钥授予权限"
    input_schema = {
        "type": "object",
        "properties": {
            "apiKeyId": {"type": "string", "description": "密钥 ID"},
            "batchDatas": {
                "type": "array",
                "description": "权限批量数据数组",
                "items": {
                    "type": "object",
                    "properties": {
                        "connectionId": {"type": "string", "description": "数据源 ID"},
                        "permissionLevel": {"type": "string", "enum": ["connection", "database", "table"], "description": "权限级别"},
                        "permissionType": {"type": "string", "description": "权限类型（逗号分隔）"},
                        "databaseName": {"type": "string", "description": "数据库名（level=database/table 时）"},
                        "tableName": {"type": "string", "description": "表名（level=table 时）"},
                    },
                    "required": ["connectionId", "permissionLevel", "permissionType"],
                },
            },
        },
        "required": ["apiKeyId", "batchDatas"],
    }

    async def execute(self, args: dict) -> dict:
        return await self.client.post("/datasource/api_key/permission/grant_batch", json_data=args)


@register_tool("revoke_api_key_permissions")
class RevokeApiKeyPermissionsTool(ToolDef):
    name = "revoke_api_key_permissions"
    description = "撤销/删除 API 密钥已授予的权限（按权限记录 ID）"
    input_schema = {
        "type": "object",
        "properties": {
            "permissionIds": {
                "type": "array",
                "items": {"type": "string"},
                "description": (
                    "权限记录 ID 列表。"
                    "先从 get_api_key_permissions 获取，"
                    "取 connectionPermissions / databasePermissions / tablePermissions 中每项的 id 字段"
                ),
            },
        },
        "required": ["permissionIds"],
    }

    async def execute(self, args: dict) -> dict:
        args = dict(args)
        permission_ids = args.pop("permissionIds", None) or []
        # 过滤掉空字符串/None，防止拼接出类似 "1,,2" 的非法 ID
        permission_ids = [pid for pid in permission_ids if pid is not None and str(pid).strip()]
        if not permission_ids:
            raise ValueError("permissionIds 不能为空")
        ids = ",".join(str(pid).strip() for pid in permission_ids)
        return await self.client.delete(f"/datasource/api_key/permission/{ids}")
