from __future__ import annotations

from typing import List, Optional, Sequence

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


class FactContextWindowService:
    def __init__(self, fact_service: FactServicePort, window: int = 5):
        self._fact_service = fact_service
        self._window = max(0, int(window))

    def build_fact_context(self, belief) -> List[str]:
        resolved_context = self._resolve_facts(belief)
        if resolved_context is None:
            return []
        _, fact_list = resolved_context
        if not fact_list:
            return []
        anchor_fact = fact_list[0]
        window_facts = collect_fact_window(anchor_fact, window=self._window)
        return _format_facts_concat(window_facts)

    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


def _format_facts_concat(facts: Sequence) -> List[str]:
    texts: List[str] = []
    for fact in facts:
        text = get_fact_text(fact)
        cleaned = text.strip()
        if cleaned and not _looks_like_question(cleaned):
            texts.append(cleaned)
    return texts


def _looks_like_question(text: str) -> bool:
    return "?" in text
