"""Query the institutional knowledge base."""

from fliiq.runtime.knowledge.retrieval import (
    format_records_for_prompt,
    retrieve_by_domain,
    retrieve_by_file,
    search_knowledge,
)
from fliiq.runtime.knowledge.store import KnowledgeStore


async def handler(params: dict) -> dict:
    """Search and retrieve knowledge records."""
    store = KnowledgeStore.from_fliiq_dir()
    max_results = params.get("max_results", 10)

    # File-anchored query (includes drift detection)
    if params.get("file"):
        results = retrieve_by_file(store, params["file"], max_records=max_results)
        if not results:
            return {"records": "No knowledge records anchored to this file.", "count": 0}
        formatted = format_records_for_prompt(results)
        return {"records": formatted, "count": len(results)}

    # Domain-only query
    if params.get("domain") and not params.get("query"):
        records = retrieve_by_domain(store, params["domain"], max_records=max_results)
        if not records:
            return {"records": f"No knowledge records in domain '{params['domain']}'.", "count": 0}
        formatted = format_records_for_prompt(records)
        return {"records": formatted, "count": len(records)}

    # Keyword search (with optional domain/type/tags filters)
    query = params.get("query", "")
    if not query:
        # No query, no domain, no file — list recent records
        records = store.list_records(limit=max_results)
        if not records:
            return {"records": "Knowledge base is empty.", "count": 0}
        formatted = format_records_for_prompt(records)
        return {"records": formatted, "count": len(records)}

    records = search_knowledge(
        store,
        query,
        max_results=max_results,
        domain=params.get("domain"),
        record_type=params.get("type"),
        tags=params.get("tags"),
    )
    if not records:
        return {"records": "No matching knowledge records found.", "count": 0}

    formatted = format_records_for_prompt(records)
    return {"records": formatted, "count": len(records)}
