"""系统信息工具"""

import json

from mcp.types import Tool, TextContent

from trailbase_mcp.client.client import TrailBaseClient


def get_info_tools() -> list[Tool]:
    """获取系统信息相关工具"""
    return [
        Tool(
            name="info.version",
            description="获取版本信息",
            inputSchema={
                "type": "object",
                "properties": {},
            },
        ),
    ]


async def handle_info_version(
    client: TrailBaseClient,
) -> list[TextContent]:
    """处理 info.version 工具调用"""
    try:
        result = client.http.get("/api/_admin/info")
        # TrailBase API 返回的字段：
        # - compiler: Option<String> - 编译器信息
        # - commit_hash: Option<String> - Git commit hash
        # - commit_date: Option<String> - Git commit 日期
        # - git_version: Option<[String, number]> - Git 版本 (tag, commits_since)
        # - threads: number - 线程数
        # - command_line_arguments: Option<Array<String>> - 命令行参数
        
        # 提取 git_version 元组
        git_version = result.get("git_version")
        git_tag = None
        commits_since = None
        if git_version and isinstance(git_version, list) and len(git_version) >= 2:
            git_tag = git_version[0]  # tag
            commits_since = git_version[1]  # commits_since
        
        # 构建版本信息，保留原始字段并添加友好映射
        version_info = {
            # 原始字段
            "compiler": result.get("compiler"),
            "commit_hash": result.get("commit_hash"),
            "commit_date": result.get("commit_date"),
            "git_version": git_version,
            "threads": result.get("threads"),
            "command_line_arguments": result.get("command_line_arguments"),
            # 友好映射字段
            "version": result.get("commit_hash"),  # 使用 commit_hash 作为版本标识
            "git_tag": git_tag,
            "commits_since": commits_since,
            "build": result.get("compiler"),  # 使用 compiler 作为构建信息
        }
        return [TextContent(type="text", text=json.dumps(version_info, ensure_ascii=False))]
    except Exception as e:
        return [TextContent(type="text", text=json.dumps({"error": str(e)}, ensure_ascii=False))]

