from __future__ import annotations

from typing import Optional, List

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


class FactContextBuilder:
    def __init__(self, fact_service: FactServicePort):
        self._fact_service = fact_service

    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 fact.text
        ]
        window_facts = collect_fact_window(anchor_fact, window=5)
        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):
        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
