"""事务工具"""

import json
from typing import Any

from mcp.types import Tool, TextContent

from trailbase_mcp.client.client import TrailBaseClient


def get_tx_tools() -> list[Tool]:
    """获取事务相关工具"""
    return [
        Tool(
            name="tx.execute",
            description="执行事务",
            inputSchema={
                "type": "object",
                "properties": {
                    "steps": {
                        "type": "array",
                        "items": {
                            "type": "object",
                            "properties": {
                                "op": {
                                    "type": "string",
                                    "enum": ["create", "update", "delete"],
                                    "description": "操作类型",
                                },
                                "api": {"type": "string", "description": "API 名称"},
                                "id": {"type": "string", "description": "记录 ID（update/delete 需要）"},
                                "data": {"type": "object", "description": "数据（create/update 需要）"},
                            },
                            "required": ["op", "api"],
                        },
                        "description": "事务步骤",
                    },
                    "stop_on_error": {
                        "type": "boolean",
                        "description": "遇到错误时停止",
                    },
                },
                "required": ["steps"],
            },
        ),
    ]


async def handle_tx_execute(
    client: TrailBaseClient,
    steps: list[dict[str, Any]],
    stop_on_error: bool | None = None,
) -> list[TextContent]:
    """处理 tx.execute 工具调用"""
    try:
        payload: dict[str, Any] = {"steps": steps}
        if stop_on_error is not None:
            payload["stop_on_error"] = stop_on_error

        result = client.http.post("/api/transaction/v1", json=payload)
        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))]

