"""日志与监控工具"""

import json
from typing import Any

from mcp.types import Tool, TextContent

from trailbase_mcp.client.client import TrailBaseClient


def get_logs_tools() -> list[Tool]:
    """获取日志相关工具"""
    return [
        Tool(
            name="logs.query",
            description="查询日志",
            inputSchema={
                "type": "object",
                "properties": {
                    "level": {"type": "string", "description": "日志级别"},
                    "route": {"type": "string", "description": "路由"},
                    "user": {"type": "string", "description": "用户"},
                    "since": {"type": "string", "description": "开始时间"},
                    "until": {"type": "string", "description": "结束时间"},
                    "limit": {"type": "integer", "description": "返回数量限制"},
                },
            },
        ),
        Tool(
            name="logs.tail",
            description="实时日志流（流式）",
            inputSchema={
                "type": "object",
                "properties": {
                    "level_min": {"type": "string", "description": "最低日志级别"},
                    "follow": {"type": "boolean", "description": "是否持续跟踪"},
                },
            },
        ),
        Tool(
            name="metrics.overview",
            description="获取系统指标概览",
            inputSchema={
                "type": "object",
                "properties": {},
            },
        ),
    ]


async def handle_logs_query(
    client: TrailBaseClient,
    level: str | None = None,
    route: str | None = None,
    user: str | None = None,
    since: str | None = None,
    until: str | None = None,
    limit: int | None = None,
) -> list[TextContent]:
    """处理 logs.query 工具调用"""
    try:
        params: dict[str, Any] = {}
        if level:
            params["level"] = level
        if route:
            params["route"] = route
        if user:
            params["user"] = user
        if since:
            params["since"] = since
        if until:
            params["until"] = until
        if limit:
            params["limit"] = limit

        result = client.http.get("/api/_admin/logs", 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_logs_tail(
    client: TrailBaseClient,
    level_min: str | None = None,
    follow: bool | None = None,
) -> list[TextContent]:
    """处理 logs.tail 工具调用"""
    try:
        params: dict[str, Any] = {}
        if level_min:
            params["level_min"] = level_min
        if follow:
            params["follow"] = follow

        result = client.http.get("/api/_admin/logs/tail", 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),
                        "note": "Streaming logs may not be fully supported via HTTP API",
                    },
                    ensure_ascii=False
                ),
            )
        ]


async def handle_metrics_overview(
    client: TrailBaseClient,
) -> list[TextContent]:
    """处理 metrics.overview 工具调用"""
    try:
        info = client.http.get("/api/_admin/info")
        metrics: dict[str, Any] = {
            "uptime_s": info.get("uptime_s", 0),
            "db_size_bytes": info.get("db_size_bytes", 0),
        }
        if "qps" in info:
            metrics["qps"] = info["qps"]
        if "p50_ms" in info:
            metrics["p50_ms"] = info["p50_ms"]
        if "p99_ms" in info:
            metrics["p99_ms"] = info["p99_ms"]

        return [TextContent(type="text", text=json.dumps(metrics, ensure_ascii=False))]
    except Exception as e:
        return [TextContent(type="text", text=json.dumps({"error": str(e)}, ensure_ascii=False))]

