"""
Mind CLI — 能力扫描器。

扫描本地可用的内置工具和 MCP Server，生成 capability report
供 Tunnel 握手时上报给 Cloud。
"""

import os
import platform
from typing import Any

import mindcli


# ── 内置工具注册表 ────────────────────────────────────
# 只暴露 Cloud 端有意义的本地工具（文件操作、终端、搜索等）
# 浏览器工具、TTS 等纯交互工具不上报
_BUILTIN_TOOLS: list[dict[str, str]] = [
    {"name": "terminal",       "type": "builtin", "desc": "执行终端命令"},
    {"name": "file_read",      "type": "builtin", "desc": "读取本地文件"},
    {"name": "file_write",     "type": "builtin", "desc": "写入本地文件"},
    {"name": "file_ops",       "type": "builtin", "desc": "文件操作（复制/移动/删除）"},
    {"name": "grep",           "type": "builtin", "desc": "文本搜索"},
    {"name": "code_execution", "type": "builtin", "desc": "执行代码片段"},
]


def scan_capabilities() -> dict[str, Any]:
    """
    扫描本地可用工具，返回 capability report。

    返回格式：
    {
        "version": "0.1.0",
        "vendor": "16f9d020",
        "platform": "Darwin",
        "arch": "arm64",
        "python": "3.12.11",
        "tools": [
            {"name": "terminal", "type": "builtin", "desc": "..."},
            ...
        ],
        "mcp_servers": []  # Phase 2+ 从 config.yaml 读取
    }
    """
    import sys

    return {
        "version": mindcli.__version__,
        "vendor": _get_vendor_commit(),
        "platform": platform.system(),
        "arch": platform.machine(),
        "python": f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}",
        "tools": list(_BUILTIN_TOOLS),
        "mcp_servers": _scan_mcp_servers(),
    }


def get_tool_names() -> list[str]:
    """返回所有内置工具名称列表。"""
    return [t["name"] for t in _BUILTIN_TOOLS]


def _scan_mcp_servers() -> list[dict[str, str]]:
    """
    扫描用户配置的第三方 MCP Server。

    TODO: 从 ~/.mindcli/config.yaml 的 mcp_servers 段读取。
    """
    return []


def _get_vendor_commit() -> str:
    commit_file = os.path.join(mindcli._VENDOR_DIR, "HERMES_COMMIT")
    try:
        with open(commit_file) as f:
            return f.read().strip()
    except FileNotFoundError:
        return "unknown"
