"""
Text Chunker
Generated by vai v{{vaiVersion}} on {{generatedAt}}

Strategy: {{chunkStrategy}}
Size: {{chunkSize}} characters
Overlap: {{chunkOverlap}} characters
"""

from typing import List


def chunk_text(
    text: str,
    size: int = {{chunkSize}},
    overlap: int = {{chunkOverlap}},
) -> List[str]:
    """
    Chunk text using recursive splitting with smart boundaries.
    
    Args:
        text: Text to chunk
        size: Maximum chunk size in characters
        overlap: Overlap between chunks
        
    Returns:
        List of text chunks
    """
    separators = ["\n\n", "\n", ". ", " "]
    
    def split_recursive(text: str, sep_index: int = 0) -> List[str]:
        if len(text) <= size:
            stripped = text.strip()
            return [stripped] if stripped else []
        
        if sep_index >= len(separators):
            # Fall back to fixed-size split
            chunks = []
            start = 0
            while start < len(text):
                chunk = text[start:start + size].strip()
                if chunk:
                    chunks.append(chunk)
                start += size - overlap
            return chunks
        
        separator = separators[sep_index]
        parts = text.split(separator)
        chunks = []
        current = ""
        
        for part in parts:
            potential = f"{current}{separator}{part}" if current else part
            
            if len(potential) <= size:
                current = potential
            else:
                if current:
                    chunks.extend(split_recursive(current, sep_index + 1))
                current = part
        
        if current:
            chunks.extend(split_recursive(current, sep_index + 1))
        
        return chunks
    
    return split_recursive(text)


def chunk_markdown(text: str, size: int = {{chunkSize}}, overlap: int = {{chunkOverlap}}) -> List[str]:
    """
    Chunk markdown with header awareness.
    Tries to keep sections together when possible.
    """
    import re
    
    # Split by headers (## or ###)
    header_pattern = r"(^#{1,3}\s+.+$)"
    parts = re.split(header_pattern, text, flags=re.MULTILINE)
    
    chunks = []
    current = ""
    
    for part in parts:
        if not part.strip():
            continue
        
        potential = f"{current}\n\n{part}" if current else part
        
        if len(potential) <= size:
            current = potential
        else:
            if current:
                # Chunk the current section
                chunks.extend(chunk_text(current, size, overlap))
            current = part
    
    if current:
        chunks.extend(chunk_text(current, size, overlap))
    
    return chunks


if __name__ == "__main__":
    # Test chunking
    sample = """
    # Introduction
    
    This is a sample document for testing the chunker.
    It contains multiple paragraphs and sections.
    
    ## Section 1
    
    Lorem ipsum dolor sit amet, consectetur adipiscing elit.
    Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
    
    ## Section 2
    
    Ut enim ad minim veniam, quis nostrud exercitation ullamco.
    Duis aute irure dolor in reprehenderit in voluptate velit.
    """
    
    chunks = chunk_text(sample)
    print(f"Created {len(chunks)} chunks:")
    for i, chunk in enumerate(chunks):
        print(f"\n--- Chunk {i + 1} ({len(chunk)} chars) ---")
        print(chunk[:200] + "..." if len(chunk) > 200 else chunk)
