from __future__ import annotations

from typing import Optional, List, Protocol

from analogai.deepthink.messaging.fact.utils.fact_utils import (
    collect_fact_window,
    format_fact_summary,
    get_belief_id,
    get_statement_id,
)


class FactServicePort(Protocol):
    def get_facts_for_belief(self, belief_id: str) -> list:
        ...

    def get_facts_for_statement(self, statement_id: str) -> list:
        ...


class FactContextBuilder:
    def __init__(self, fact_service: FactServicePort, time_window_seconds: int | None = None):
        self._fact_service = fact_service
        self._time_window_seconds = time_window_seconds

    def build_belief_context(self, belief) -> Optional[str]:
        resolved_context = self._resolve_facts(belief)
        if not resolved_context:
            return None
        _, fact_list = resolved_context
        if not fact_list:
            return None
        anchor_fact = fact_list[0]
        summaries: List[str] = [
            format_fact_summary(fact)
            for fact in fact_list
            if getattr(fact, "text", None)
        ]
        window_facts = collect_fact_window(
            anchor_fact,
            window=5,
            time_window_seconds=self._time_window_seconds,
        )
        for neighbor_fact in window_facts:
            summaries.append(format_fact_summary(neighbor_fact))
        filtered_summaries = [summary for summary in summaries if summary]
        return "; ".join(filtered_summaries) if filtered_summaries else None

    def _resolve_facts(self, belief) -> Optional[tuple[str, list]]:
        belief_id = get_belief_id(belief)
        if belief_id:
            fact_list = self._fact_service.get_facts_for_belief(belief_id)
            if fact_list:
                turn_id = fact_list[0].turn_id
                if turn_id:
                    return turn_id, fact_list
        statement_id = get_statement_id(belief)
        if statement_id:
            fact_list = self._fact_service.get_facts_for_statement(statement_id)
            if fact_list:
                turn_id = fact_list[0].turn_id
                if turn_id:
                    return turn_id, fact_list
        return None


__all__ = ["FactContextBuilder"]
