"""WASM 组件管理工具"""

import json
from typing import Any

from mcp.types import Tool, TextContent

from trailbase_mcp.client.client import TrailBaseClient


def get_wasm_tools() -> list[Tool]:
    """获取 WASM 相关工具"""
    return [
        Tool(
            name="wasm.list_available",
            description="列出可用的 WASM 组件",
            inputSchema={
                "type": "object",
                "properties": {},
            },
        ),
        Tool(
            name="wasm.installed",
            description="列出已安装的 WASM 组件",
            inputSchema={
                "type": "object",
                "properties": {},
            },
        ),
        Tool(
            name="wasm.add",
            description="安装 WASM 组件",
            inputSchema={
                "type": "object",
                "properties": {
                    "reference": {
                        "type": "string",
                        "description": "组件引用（名称/URL/本地路径）",
                    },
                },
                "required": ["reference"],
            },
        ),
        Tool(
            name="wasm.remove",
            description="移除 WASM 组件",
            inputSchema={
                "type": "object",
                "properties": {
                    "reference": {
                        "type": "string",
                        "description": "组件引用（名称/路径）",
                    },
                },
                "required": ["reference"],
            },
        ),
        Tool(
            name="wasm.update_all",
            description="更新所有 WASM 组件",
            inputSchema={
                "type": "object",
                "properties": {},
            },
        ),
    ]


async def handle_wasm_list_available(
    client: TrailBaseClient,
) -> list[TextContent]:
    """处理 wasm.list_available 工具调用"""
    try:
        # 尝试从 Admin API 获取
        result = client.http.get("/api/_admin/wasm/components/available")
        return [TextContent(type="text", text=json.dumps(result, ensure_ascii=False))]
    except Exception:
        # Fallback: 返回空列表或错误提示
        return [
            TextContent(
                type="text",
                text=json.dumps(
                    {
                        "components": [],
                        "note": "Available components list not available via API. Use trail CLI instead.",
                    },
                    ensure_ascii=False
                ),
            )
        ]


async def handle_wasm_installed(
    client: TrailBaseClient,
) -> list[TextContent]:
    """处理 wasm.installed 工具调用"""
    try:
        result = client.http.get("/api/_admin/wasm/components/installed")
        return [TextContent(type="text", text=json.dumps(result, ensure_ascii=False))]
    except Exception:
        return [
            TextContent(
                type="text",
                text=json.dumps(
                    {
                        "components": [],
                        "note": "Installed components list not available via API. Use trail CLI instead.",
                    },
                    ensure_ascii=False
                ),
            )
        ]


async def handle_wasm_add(
    client: TrailBaseClient,
    reference: str,
) -> list[TextContent]:
    """处理 wasm.add 工具调用"""
    try:
        result = client.http.post("/api/_admin/wasm/components", json={"reference": reference})
        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),
                        "note": "If API unavailable, use 'trail components add' CLI command",
                    },
                    ensure_ascii=False
                ),
            )
        ]


async def handle_wasm_remove(
    client: TrailBaseClient,
    reference: str,
) -> list[TextContent]:
    """处理 wasm.remove 工具调用"""
    try:
        client.http.delete(f"/api/_admin/wasm/components/{reference}")
        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),
                        "note": "If API unavailable, use 'trail components remove' CLI command",
                    },
                    ensure_ascii=False
                ),
            )
        ]


async def handle_wasm_update_all(
    client: TrailBaseClient,
) -> list[TextContent]:
    """处理 wasm.update_all 工具调用"""
    try:
        result = client.http.post("/api/_admin/wasm/components/update-all")
        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),
                        "note": "If API unavailable, use 'trail components update' CLI command",
                    },
                    ensure_ascii=False
                ),
            )
        ]

