from __future__ import annotations

from dataclasses import dataclass
from typing import Optional, Protocol

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


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


@dataclass(frozen=True)
class SentenceBatcher:
    max_sentences_per_input: int

    def chunk_input(self, input_text: str) -> list[str]:
        return chunk_sentences(input_text, self.max_sentences_per_input)

    def process_chat(
        self,
        input_text: str,
        handler: ChunkHandler,
    ) -> Optional[str]:
        chunks = self.chunk_input(input_text)
        if not chunks:
            return None
        last_response: Optional[str] = None
        for chunk in chunks:
            last_response = handler.handle(chunk)
        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
