from __future__ import annotations

import re
from typing import List


_SENTENCE_SPLIT_REGEX = re.compile(r"(?<=[.!?])\s+")


def split_into_sentences(text: str) -> List[str]:
    if text is None:
        raise ValueError("text cannot be None")
    cleaned = text.strip()
    if not cleaned:
        return []
    return [sentence for sentence in _SENTENCE_SPLIT_REGEX.split(cleaned) if sentence]


def chunk_sentences(text: str, max_sentences_per_chunk: int) -> List[str]:
    if text is None:
        raise ValueError("text cannot be None")
    cleaned = text.strip()
    if not cleaned:
        return []
    max_per_chunk = max(1, int(max_sentences_per_chunk))
    sentences = split_into_sentences(cleaned)
    chunks: List[str] = []
    current: List[str] = []
    for sentence in sentences:
        if not sentence:
            continue
        current.append(sentence)
        if len(current) >= max_per_chunk:
            chunks.append(" ".join(current).strip())
            current = []
    if current:
        chunks.append(" ".join(current).strip())
    return chunks
