from fliiq.runtime.config import resolve_fliiq_dir
from fliiq.runtime.memory.manager import MemoryManager
from fliiq.runtime.memory.retrieval import search_memories


async def handler(params: dict) -> dict:
    """Search memory files or list skill memories."""
    manager = MemoryManager(resolve_fliiq_dir() / "memory")

    if params.get("list_skills"):
        skills = manager.list_skill_memories()
        if not skills:
            return {"results": "No skill memories found."}
        return {"results": "Available skill memories:\n" + "\n".join(f"- {s}" for s in skills)}

    query = params.get("query")
    if not query:
        return {"results": "No query provided. Use 'query' to search or 'list_skills: true' to list skill memories."}

    ignore_case = params.get("ignore_case", True)
    max_results = params.get("max_results", 50)

    results = search_memories(manager, query, ignore_case=ignore_case, max_results=max_results)
    if not results:
        return {"results": f"No matches found for: {query}"}

    lines = []
    for r in results:
        lines.append(f"{r.file_name}:{r.line_number}: {r.line}")
    return {"results": "\n".join(lines)}
