class DocumentChunker:
    """按段落优先切分，超长段落使用字符重叠保留上下文。"""

    def __init__(self, *, max_chars: int = 700, overlap_chars: int = 100) -> None:
        if max_chars <= 0:
            raise ValueError("max_chars必须大于0")
        if overlap_chars < 0 or overlap_chars >= max_chars:
            raise ValueError("overlap_chars必须大于等于0且小于max_chars")
        self._max_chars = max_chars
        self._overlap_chars = overlap_chars

    def split(self, content: str) -> list[str]:
        paragraphs = [
            paragraph.strip()
            for paragraph in content.replace("\r\n", "\n").replace("\r", "\n").split("\n\n")
            if paragraph.strip()
        ]
        chunks: list[str] = []
        for paragraph in paragraphs:
            if len(paragraph) <= self._max_chars:
                chunks.append(paragraph)
                continue
            chunks.extend(self._split_long_paragraph(paragraph))
        return chunks

    def _split_long_paragraph(self, paragraph: str) -> list[str]:
        step = self._max_chars - self._overlap_chars
        return [
            paragraph[start : start + self._max_chars]
            for start in range(0, len(paragraph), step)
            if paragraph[start : start + self._max_chars]
        ]
