"""Record API 工具"""

import json
from typing import Any

from mcp.types import Tool, TextContent

from trailbase_mcp.client.client import TrailBaseClient


def get_records_tools() -> list[Tool]:
    """获取 Record API 相关工具"""
    return [
        Tool(
            name="records.list",
            description="列出记录",
            inputSchema={
                "type": "object",
                "properties": {
                    "api": {"type": "string", "description": "API 名称"},
                    "filter": {"type": "object", "description": "过滤条件"},
                    "order_by": {"type": "string", "description": "排序字段"},
                    "limit": {"type": "integer", "description": "返回数量限制"},
                    "page_token": {"type": "string", "description": "分页令牌"},
                    "expand": {
                        "type": "array",
                        "items": {"type": "string"},
                        "description": "展开的关联字段",
                    },
                },
                "required": ["api"],
            },
        ),
        Tool(
            name="records.get",
            description="获取单个记录",
            inputSchema={
                "type": "object",
                "properties": {
                    "api": {"type": "string", "description": "API 名称"},
                    "id": {"type": "string", "description": "记录 ID"},
                },
                "required": ["api", "id"],
            },
        ),
        Tool(
            name="records.create",
            description="创建记录",
            inputSchema={
                "type": "object",
                "properties": {
                    "api": {"type": "string", "description": "API 名称"},
                    "data": {"type": "object", "description": "记录数据"},
                },
                "required": ["api", "data"],
            },
        ),
        Tool(
            name="records.update",
            description="更新记录",
            inputSchema={
                "type": "object",
                "properties": {
                    "api": {"type": "string", "description": "API 名称"},
                    "id": {"type": "string", "description": "记录 ID"},
                    "data": {"type": "object", "description": "更新的数据"},
                },
                "required": ["api", "id", "data"],
            },
        ),
        Tool(
            name="records.delete",
            description="删除记录",
            inputSchema={
                "type": "object",
                "properties": {
                    "api": {"type": "string", "description": "API 名称"},
                    "id": {"type": "string", "description": "记录 ID"},
                },
                "required": ["api", "id"],
            },
        ),
        Tool(
            name="records.schema",
            description="获取 API Schema",
            inputSchema={
                "type": "object",
                "properties": {
                    "api": {"type": "string", "description": "API 名称"},
                },
                "required": ["api"],
            },
        ),
        Tool(
            name="records.apis",
            description="列出所有 Record APIs",
            inputSchema={
                "type": "object",
                "properties": {},
            },
        ),
    ]


async def handle_records_list(
    client: TrailBaseClient,
    api: str,
    filter: dict[str, Any] | None = None,
    order_by: str | None = None,
    limit: int | None = None,
    page_token: str | None = None,
    expand: list[str] | None = None,
) -> list[TextContent]:
    """处理 records.list 工具调用"""
    try:
        # 检查 record API 是否存在
        config = client.http.get("/api/_admin/config")
        record_apis = config.get("record_apis", {})
        if api not in record_apis:
            return [TextContent(type="text", text=f'{{"error": "Record API \\"{api}\\" not found. Available APIs: {list(record_apis.keys())}"}}')]
        
        params: dict[str, Any] = {}
        if filter:
            params["filter"] = filter
        if order_by:
            params["order_by"] = order_by
        if limit:
            params["limit"] = limit
        if page_token:
            params["page_token"] = page_token
        if expand:
            params["expand"] = expand

        result = client.http.get(f"api/records/v1/{api}", params=params)
        return [TextContent(type="text", text=json.dumps(result, ensure_ascii=False))]
    except Exception as e:
        return [TextContent(type="text", text=json.dumps({"error": str(e)}, ensure_ascii=False))]


async def handle_records_get(
    client: TrailBaseClient,
    api: str,
    id: str,
) -> list[TextContent]:
    """处理 records.get 工具调用"""
    try:
        result = client.http.get(f"/api/records/v1/{api}/{id}")
        return [TextContent(type="text", text=json.dumps({"item": result}, ensure_ascii=False))]
    except Exception as e:
        return [TextContent(type="text", text=json.dumps({"error": str(e)}, ensure_ascii=False))]


async def handle_records_create(
    client: TrailBaseClient,
    api: str,
    data: dict[str, Any],
) -> list[TextContent]:
    """处理 records.create 工具调用"""
    try:
        result = client.http.post(f"/api/records/v1/{api}", json=data)
        return [TextContent(type="text", text=json.dumps(result, ensure_ascii=False))]
    except Exception as e:
        return [TextContent(type="text", text=json.dumps({"error": str(e)}, ensure_ascii=False))]


async def handle_records_update(
    client: TrailBaseClient,
    api: str,
    id: str,
    data: dict[str, Any],
) -> list[TextContent]:
    """处理 records.update 工具调用"""
    try:
        result = client.http.patch(f"/api/records/v1/{api}/{id}", json=data)
        return [TextContent(type="text", text=json.dumps({"item": result}, ensure_ascii=False))]
    except Exception as e:
        return [TextContent(type="text", text=json.dumps({"error": str(e)}, ensure_ascii=False))]


async def handle_records_delete(
    client: TrailBaseClient,
    api: str,
    id: str,
) -> list[TextContent]:
    """处理 records.delete 工具调用"""
    try:
        client.http.delete(f"/api/records/v1/{api}/{id}")
        return [TextContent(type="text", text=json.dumps({"ok": True}, ensure_ascii=False))]
    except Exception as e:
        return [TextContent(type="text", text=json.dumps({"error": str(e)}, ensure_ascii=False))]


async def handle_records_schema(
    client: TrailBaseClient,
    api: str,
) -> list[TextContent]:
    """处理 records.schema 工具调用"""
    try:
        # 检查 record API 是否存在
        config = client.http.get("/api/_admin/config")
        record_apis = config.get("record_apis", {})
        if api not in record_apis:
            return [TextContent(type="text", text=json.dumps({"error": f'Record API "{api}" not found. Available APIs: {list(record_apis.keys())}'}, ensure_ascii=False))]
        
        result = client.http.get(f"api/records/v1/{api}/schema")
        return [TextContent(type="text", text=json.dumps({"json_schema": result}, ensure_ascii=False))]
    except Exception as e:
        return [TextContent(type="text", text=json.dumps({"error": str(e)}, ensure_ascii=False))]


async def handle_records_apis(
    client: TrailBaseClient,
) -> list[TextContent]:
    """处理 records.apis 工具调用"""
    try:
        # 尝试从配置中获取
        config = client.http.get("/api/_admin/config")
        record_apis = config.get("record_apis", {})
        apis = []
        for name, api_config in record_apis.items():
            apis.append(
                {
                    "name": name,
                    "table": api_config.get("table"),
                    "acl": api_config.get("acl"),
                    "schema_summary": api_config.get("schema"),
                }
            )
        return [TextContent(type="text", text=json.dumps({"apis": apis}, ensure_ascii=False))]
    except Exception as e:
        return [TextContent(type="text", text=json.dumps({"error": str(e)}, ensure_ascii=False))]

