"""search_memories -- domain logic for RAG memory retrieval.

Extracted from app/tools/search_memories_tool.py.
No sqlalchemy / fastapi / redis imports allowed.

Accepts a MemoryVectorStore protocol.
"""
from __future__ import annotations

import logging
from dataclasses import dataclass, field

from kokoro_chat.storage.protocol import MemorySearchResult, MemoryVectorStore

logger = logging.getLogger(__name__)


@dataclass
class SearchMemoriesResult:
    """Result of a memory search operation."""

    success: bool
    memories: list[MemorySearchResult] = field(default_factory=list)
    error: str = ""


async def search_memories(
    store: MemoryVectorStore,
    character_id: str,
    user_id: str,
    query: str,
    limit: int = 5,
) -> SearchMemoriesResult:
    """Search past conversation memories by semantic similarity.

    Parameters
    ----------
    store : MemoryVectorStore
        Protocol-based memory storage.
    character_id, user_id : str
        Identifiers for the character/user pair.
    query : str
        The search query.
    limit : int
        Maximum number of memories to return.
    """
    query = query.strip()
    if not query:
        return SearchMemoriesResult(success=False, error="query must not be empty")

    try:
        results = await store.search(
            query=query,
            character_id=character_id,
            user_id=user_id,
            top_k=limit,
        )

        logger.info(
            "search_memories for user=%s char=%s query=%r returned %d results",
            user_id, character_id, query[:50], len(results),
        )
        return SearchMemoriesResult(success=True, memories=results)

    except Exception as e:
        logger.error("search_memories failed: %s", e, exc_info=True)
        return SearchMemoriesResult(success=False, error=str(e))
