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

from navi.memory.store import MemoryStore
from navi.tools.base import current_user_id

from .base import Tool, ToolResult


class MemorySearchTool(Tool):
    name = "memory_search"
    description = (
        "Search long-term memory for facts about the user. "
        "Call this when the injected summary does not contain the specific information you need: "
        "server addresses, credentials, preferences, project details, past decisions, ongoing work. "
        "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")

        user_id = current_user_id.get(None)
        facts = await self._store.search_facts(query, user_id=user_id, 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)
