import re

SENTENCE_RE = re.compile(
    r'[.?!](\s*\r?\n|\s+(?=[A-Z\u0410-\u042f]))'
)
SIZE_LIMIT = 50000


def split_text(text: str) -> list[dict]:
    """Split text into sentence chunks with positions.

    Returns list of {"text": str, "start": int, "end": int}.
    Based on Glvrd's SplitText logic.
    """
    if not text or not text.strip():
        return []

    chunks = []
    start = 0

    for m in SENTENCE_RE.finditer(text):
        end = m.end()
        if end > SIZE_LIMIT:
            break
        chunks.append({
            "text": text[start:end],
            "start": start,
            "end": end,
        })
        start = end

    # Remainder
    if start < len(text) and len(text) <= SIZE_LIMIT:
        remainder = text[start:]
        if remainder.strip():
            chunks.append({
                "text": remainder,
                "start": start,
                "end": len(text),
            })

    # If no splits found, return whole text
    if not chunks and text.strip():
        chunks.append({"text": text, "start": 0, "end": len(text)})

    return chunks
