from __future__ import annotations

from dataclasses import dataclass
from typing import Optional, Protocol

from analogai.deepthink.messaging.text.sentence_chunker import (
    chunk_facts,
    split_into_sentences,
)


class FactHandler(Protocol):
    def handle(self, fact: str) -> Optional[str]:
        ...


@dataclass(frozen=True)
class FactBatcher:
    max_paragraphs_per_fact: int

    def chunk_facts(self, input_text: str) -> list[str]:
        return chunk_facts(input_text, self.max_paragraphs_per_fact)

    def process_chat(
        self,
        input_text: str,
        handler: FactHandler,
    ) -> Optional[str]:
        facts = self.chunk_facts(input_text)
        if not facts:
            return None
        last_response: Optional[str] = None
        for fact in facts:
            last_response = handler.handle(fact)
        if not self._last_sentence_is_question(input_text):
            if last_response is not None:
                return last_response
            if self._is_single_sentence(input_text):
                return input_text.strip()
            return input_text.strip() or None
        return last_response

    def _last_sentence_is_question(self, input_text: str) -> bool:
        sentences = split_into_sentences(input_text)
        if not sentences:
            return False
        last_sentence = sentences[-1].strip()
        if not last_sentence:
            return False
        return "?" in last_sentence

    def _is_single_sentence(self, input_text: str) -> bool:
        sentences = split_into_sentences(input_text)
        return len(sentences) == 1
