from __future__ import annotations

from typing import Iterable, List, Tuple

from analogai.deepthink.application.value_objects.user_agent import UserAgent
from analogai.deepthink.messaging.question_answering.services.formatting.fact_formatter import (
    QuestionFactFormatter,
)
from analogai.deepthink.messaging.question_answering.adapters.belief_search_adapter import (
    BeliefSearchAdapter,
)
from analogai.deepthink.messaging.question_answering.adapters.notion_search_adapter import (
    NotionSearchAdapter,
)


class BeliefBackgroundInfoBuilder:
    def __init__(
        self,
        belief_retriever: BeliefSearchAdapter,
        notion_retriever: NotionSearchAdapter,
        belief_formatter: QuestionFactFormatter,
    ) -> None:
        self._belief_retriever = belief_retriever
        self._notion_retriever = notion_retriever
        self._belief_formatter = belief_formatter

    def build_background(
        self,
        user_agent: UserAgent,
        entities: Iterable[str],
    ) -> Tuple[List, List, List[str], str, int]:
        if not entities:
            return [], [], [], "", 0
        beliefs = self._belief_retriever.search_beliefs(user_agent, entities)
        notions = self._notion_retriever.search_notions(user_agent, entities)
        notions = self._notion_retriever.expand_notions_from_beliefs(user_agent, notions, beliefs)
        notion_text = self._belief_formatter.format_notions(notions)
        notion_lines = [line for line in notion_text.splitlines() if line.strip()] if notion_text else []
        belief_block = self._belief_formatter.build_fact_block_text(beliefs)
        belief_count = self._count_serialized_beliefs(beliefs)
        return beliefs, notions, notion_lines, belief_block, belief_count

    def _count_serialized_beliefs(self, beliefs: Iterable) -> int:
        count = 0
        for belief in beliefs or []:
            if self._belief_formatter.format_fact(belief):
                count += 1
        return count
