"""Tool list construction shared between Agent and SubAgentRunner."""

import logging
from pathlib import Path

from navi.config import settings
from navi.tools._internal.base import Tool

log = logging.getLogger(__name__)

_USER_ENABLED_FILE = Path(settings.tools_dir) / "enabled.json"


def load_user_enabled_tools() -> list[str]:
    try:
        import json
        return json.loads(_USER_ENABLED_FILE.read_text())
    except Exception:
        return []


def build_tool_list(
    enabled: list[str],
    mcp_servers: dict[str, list[str]] | None,
    tool_registry,
    mcp_manager,
) -> list[Tool]:
    """Resolve enabled tool names + MCP groups into concrete Tool objects."""
    names = list(enabled)
    extra = load_user_enabled_tools()
    for name in extra:
        if name not in names:
            names.append(name)

    # Expand MCP server groups into concrete tool names
    from navi.mcp.tools import build_mcp_name

    if mcp_servers and mcp_manager:
        for server_name, groups in mcp_servers.items():
            if "*" in groups:
                prefix = build_mcp_name(server_name, "")
                for tool in tool_registry.all():
                    if tool.name.startswith(prefix) and tool.name not in names:
                        names.append(tool.name)
            else:
                for group_name in groups:
                    for tool_name in mcp_manager.resolve_group(server_name, group_name):
                        full_name = build_mcp_name(server_name, tool_name)
                        if full_name not in names:
                            names.append(full_name)

    result = []
    missing = []
    for name in names:
        try:
            result.append(tool_registry.get(name))
        except Exception:
            missing.append(name)
    if missing:
        log.warning("build_tool_list missing tools: %s", missing)
    return result
