from __future__ import annotations

import json
from typing import TYPE_CHECKING

from niannian.mcp.mcp_space import resolve_mcp_memory_space
from niannian.mcp.server.tools.external_helpers import run_inbound_tool

if TYPE_CHECKING:
    from mcp.server.fastmcp import FastMCP

    from niannian.mcp.service import NianNianService


def register_external_query_tools(mcp: FastMCP, svc: NianNianService) -> None:
    @mcp.tool()
    def niannian_external_recall(project: str, function: str, query: str, limit: int = 10) -> str:
        """工具岛内检索 — records + _learned 摘要；仅返回指定 project。"""
        space = resolve_mcp_memory_space(svc, project)

        def _recall() -> str:
            from niannian.mcp.server.tools.external_data import _external_svc

            result = _external_svc(svc).recall_external(space, function, query, limit=limit)
            return json.dumps(result, ensure_ascii=False)

        return run_inbound_tool(
            svc,
            tool="niannian_external_recall",
            args_summary=f"project={space} function={function} q={query[:40]}",
            capability_id=None,
            fn=_recall,
        )

    @mcp.tool()
    def niannian_external_list(project: str, function: str = "") -> str:
        """列出 project 下 function 目录或指定 function 的记录。"""
        space = resolve_mcp_memory_space(svc, project)

        def _list() -> str:
            from niannian.mcp.server.tools.external_data import _external_svc

            result = _external_svc(svc).list_external(space, function)
            return json.dumps(result, ensure_ascii=False)

        return run_inbound_tool(
            svc,
            tool="niannian_external_list",
            args_summary=f"project={space} function={function or '*'}",
            capability_id=None,
            fn=_list,
        )

    @mcp.tool()
    def niannian_external_learn(project: str, function: str) -> str:
        """手动触发 function 摘要，写入 external/{project}/_learned/。"""
        space = resolve_mcp_memory_space(svc, project)

        def _learn() -> str:
            from niannian.mcp.server.tools.external_data import _external_svc

            result = _external_svc(svc).learn_external(space, function)
            return json.dumps(result, ensure_ascii=False)

        return run_inbound_tool(
            svc,
            tool="niannian_external_learn",
            args_summary=f"project={space} function={function}",
            capability_id=None,
            fn=_learn,
        )

    @mcp.tool()
    def niannian_external_audit(project: str, since: str = "", actor: str = "") -> str:
        """查询 external/{project}/_audit.jsonl，可按时间与 actor 过滤。"""
        space = resolve_mcp_memory_space(svc, project)

        def _audit() -> str:
            from niannian.mcp.server.tools.external_data import _external_svc

            result = _external_svc(svc).query_tool_audit(space, since=since, actor=actor)
            return json.dumps(result, ensure_ascii=False)

        return run_inbound_tool(
            svc,
            tool="niannian_external_audit",
            args_summary=f"project={space} since={since or '-'} actor={actor or '-'}",
            capability_id=None,
            fn=_audit,
        )

    @mcp.tool()
    def niannian_external_trace(project: str, record_id: str) -> str:
        """按 record_id 追溯 provenance.parent_record_id 因果链。"""
        space = resolve_mcp_memory_space(svc, project)

        def _trace() -> str:
            from niannian.mcp.server.tools.external_data import _external_svc

            result = _external_svc(svc).trace_external(space, record_id)
            return json.dumps(result, ensure_ascii=False)

        return run_inbound_tool(
            svc,
            tool="niannian_external_trace",
            args_summary=f"project={space} record_id={record_id}",
            capability_id=None,
            fn=_trace,
        )
