"""
Utility functions shared across the TopoRAG library.
"""

def split_text(text: str) -> list[str]:
    """Split text into segments, filtering out short fragments.

    Strategy (tries each in order until we get ≥ 3 segments):
    1. Split on double newlines (blank lines between paragraphs).
    2. Split on single newlines (one line per segment).
    3. Split on sentences ('. ', '? ', '! ') as a last resort.
    """
    MIN_LEN = 20

    # 1. Double-newline split
    segs = [s.strip() for s in text.split("\n\n") if len(s.strip()) >= MIN_LEN]
    if len(segs) >= 3:
        return segs

    # 2. Single-newline split
    segs = [s.strip() for s in text.split("\n") if len(s.strip()) >= MIN_LEN]
    if len(segs) >= 3:
        return segs

    # 3. Sentence split (simple punctuation-based)
    import re
    sentences = re.split(r'(?<=[.!?])\s+', text)
    segs = [s.strip() for s in sentences if len(s.strip()) >= MIN_LEN]
    return segs

def chunks(lst: list, n: int):
    """Yield successive n-sized chunks from lst."""
    for i in range(0, len(lst), n):
        yield lst[i:i + n]
