"""Memory search tool — query facts about the user from long-term memory."""

from navi.memory.store import MemoryStore

from .base import Tool, ToolResult


class MemorySearchTool(Tool):
    name = "memory_search"
    description = (
        "Search your long-term memory for facts about the user. "
        "Call this at the start of each new session with query='user profile' to load basic context. "
        "Also call it whenever the user's question might benefit from personal knowledge "
        "(location, preferences, technical environment, ongoing projects, etc.) "
        "before you answer. Returns matching facts from the memory database."
    )
    parameters = {
        "type": "object",
        "properties": {
            "query": {
                "type": "string",
                "description": (
                    "What to search for — describe the context you need. "
                    "Examples: 'user profile', 'home server', 'programming preferences', 'current projects'"
                ),
            },
        },
        "required": ["query"],
    }

    def __init__(self, memory_store: MemoryStore) -> None:
        self._store = memory_store

    async def execute(self, params: dict) -> ToolResult:
        query = params.get("query", "").strip()
        if not query:
            return ToolResult(success=False, output="Query is required.", error="missing query")

        facts = await self._store.search_facts(query, limit=15)
        if not facts:
            return ToolResult(success=True, output="No matching facts found in memory.")

        lines = [f"[{f['category']}] {f['key']}: {f['value']}" for f in facts]
        output = f"Found {len(facts)} fact(s):\n" + "\n".join(lines)
        return ToolResult(success=True, output=output)
