"""Lesson 3: three ways to split documents into retrievable chunks."""
from __future__ import annotations

import re

from .documents import Chunk, Document, title_of


def chunk_by_words(doc: Document, size: int = 120, overlap: int = 30) -> list[Chunk]:
    """Fixed-size windows of `size` words, each overlapping the previous by `overlap` words."""
    if size <= 0 or not 0 <= overlap < size:
        raise ValueError("need size > 0 and 0 <= overlap < size")
    words = doc.text.split()
    chunks, start, n = [], 0, 0
    while start < len(words):
        piece = " ".join(words[start:start + size])
        chunks.append(Chunk(f"{doc.id}#{n}", doc.id, piece, dict(doc.metadata)))
        if start + size >= len(words):
            break
        start += size - overlap
        n += 1
    return chunks


_SENTENCE_END = re.compile(r"(?<=[.!?])\s+(?=[A-Z0-9\"'(])")


def split_sentences(text: str) -> list[str]:
    out = []
    for block in re.split(r"\n\s*\n", text):
        block = " ".join(block.split())
        out += [s.strip() for s in _SENTENCE_END.split(block) if s.strip()]
    return out


def chunk_by_sentences(doc: Document, max_words: int = 120) -> list[Chunk]:
    """Pack whole sentences into chunks of at most `max_words` words (a long sentence gets its own chunk)."""
    chunks, current, count = [], [], 0
    for sentence in split_sentences(doc.text):
        n = len(sentence.split())
        if current and count + n > max_words:
            chunks.append(" ".join(current))
            current, count = [], 0
        current.append(sentence)
        count += n
    if current:
        chunks.append(" ".join(current))
    return [Chunk(f"{doc.id}#{i}", doc.id, c, dict(doc.metadata)) for i, c in enumerate(chunks)]


def chunk_markdown(doc: Document, max_words: int = 200) -> list[Chunk]:
    """One chunk per Markdown section, prefixed with its heading path so it stands on its own.

    Sections longer than max_words are split further by sentences.
    """
    doc_title = title_of(doc.text, doc.id)
    sections: list[tuple[str, list[str]]] = []
    heading, lines = doc_title, []
    for line in doc.text.splitlines():
        m = re.match(r"^(#{1,6})\s+(.*)$", line)
        if m:
            if any(x.strip() for x in lines):
                sections.append((heading, lines))
            level, text = len(m.group(1)), m.group(2).strip()
            heading = text if level == 1 else f"{doc_title} > {text}"
            lines = []
        else:
            lines.append(line)
    if any(x.strip() for x in lines):
        sections.append((heading, lines))

    chunks: list[Chunk] = []
    for heading, body_lines in sections:
        body = "\n".join(body_lines).strip()
        parts = [body]
        if len(body.split()) > max_words:
            sub = Document(doc.id, body)
            parts = [c.text for c in chunk_by_sentences(sub, max_words)]
        for part in parts:
            meta = {**doc.metadata, "section": heading}
            chunks.append(Chunk(f"{doc.id}#{len(chunks)}", doc.id, f"{heading}\n{part}", meta))
    return chunks
