from __future__ import annotations

import re
from typing import Iterable, List


def split_sentences(text: str) -> List[str]:
    if not text:
        return []
    return [s.strip() for s in re.split(r"(?<=[.!?])\s+", text.strip()) if s.strip()]


def chunk_text(text: str, max_chars: int = 160) -> Iterable[str]:
    return chunk_text_for_speech(text, max_chars=max_chars, max_sentences=3)


def chunk_text_for_speech(text: str, max_chars: int = 160, max_sentences: int = 2) -> Iterable[str]:
    if not text:
        return []
    sentences = split_sentences(text)
    chunk = ""
    sentence_count = 0
    chunks: List[str] = []
    for sentence in sentences:
        if not sentence:
            continue
        proposed = f"{chunk} {sentence}".strip() if chunk else sentence
        if (len(proposed) <= max_chars) and (sentence_count < max_sentences):
            chunk = proposed
            sentence_count += 1
            continue
        if chunk:
            chunks.append(chunk)
        if len(sentence) <= max_chars:
            chunk = sentence
            sentence_count = 1
        else:
            # Hard split long sentences.
            start = 0
            while start < len(sentence):
                end = min(start + max_chars, len(sentence))
                chunks.append(sentence[start:end].strip())
                start = end
            chunk = ""
            sentence_count = 0
    if chunk:
        chunks.append(chunk)
    return chunks
