from __future__ import annotations

from typing import List

from analogai.foundation.common.logging.app_logger import app_logger  # type: ignore[import-not-found]

from analogai.deepthink.application.value_objects.user_agent import UserAgent
from analogai.deepthink.messaging.fact.enums.fact_search_mode import FactSearchMode


class FactSearchAdapter:
    def __init__(
        self,
        fact_service,
        top_k: int = 5,
        similarity_cutoff: float | None = None,
        search_mode: FactSearchMode | None = None,
    ) -> None:
        self._fact_service = fact_service
        self._top_k = max(1, int(top_k))
        self._similarity_cutoff = similarity_cutoff
        self._search_mode = search_mode

    def search_facts(
        self,
        user_agent: UserAgent,
        query: str,
        search_mode: FactSearchMode | None = None,
    ) -> List:
        if not query or not query.strip():
            return []
        if self._fact_service is None:
            app_logger.debug("[FactSearchAdapter] fact_service unavailable")
            return []
        mode = search_mode or self._search_mode or FactSearchMode.VECTOR_THEN_TEXT
        results = self._fact_service.search_facts(
            user_id=user_agent.user_id,
            agent_id=user_agent.agent_id,
            query=query,
            top_k=self._top_k,
            similarity_cutoff=self._similarity_cutoff,
            mode=mode,
        )
        app_logger.debug(
            "[FactSearchAdapter] results=%d query='%s'",
            len(results or []),
            query.strip(),
        )
        for index, fact in enumerate(results or []):
            text = _fact_text(fact)
            if text is None:
                continue
            cleaned = str(text).strip()
            if not cleaned:
                continue
            app_logger.debug(
                "[FactSearchAdapter] result_after_vector[%d]=%s",
                index,
                cleaned,
            )
        return results

    def get_facts_for_notion(
        self,
        notion_id: str,
    ) -> List:
        if not notion_id:
            return []
        if self._fact_service is None:
            app_logger.debug("[FactSearchAdapter] fact_service unavailable for notion lookup")
            return []
        return self._fact_service.get_facts_for_notion(notion_id)


def _fact_text(fact) -> str | None:
    if fact is None:
        return None
    return fact.text
