import re

def recursive_chunk(
    text: str,
    max_size: int = 400,
    overlap: int = 50
) -> list[str]:
    """递归分块：先按段落，再按句子，再按字数"""

    # 第一优先：按段落切（双换行）
    paragraphs = re.split(r'\n\n+', text.strip())

    chunks = []
    for para in paragraphs:
        if len(para) <= max_size:
            chunks.append(para.strip())   # 段落够小，直接用
            continue

        # 段落太大：按句子切
        sentences = re.split(r'(?<=[。！？.!?])', para)
        buf, buf_len = [], 0
        for sent in sentences:
            if buf_len + len(sent) > max_size and buf:
                chunk = "".join(buf)
                chunks.append(chunk)
                # 保留重叠：最后 overlap 个字作为下一块的开头
                overlap_text = chunk[-overlap:] if len(chunk) > overlap else chunk
                buf = [overlap_text]
                buf_len = len(overlap_text)
            buf.append(sent)
            buf_len += len(sent)
        if buf:
            chunks.append("".join(buf))

    return [c.strip() for c in chunks if c.strip()]

# 使用示例
# chunks = recursive_chunk(book_text, max_size=400, overlap=50)
# print(f"共切出 {len(chunks)} 块，平均 {sum(len(c) for c in chunks)//len(chunks)} 字/块")