"""Chunking strategies.

Sizes are measured in characters to stay dependency-free. As a rough guide,
English text averages about 4 characters per token, so 2000 characters is
roughly 500 tokens. Swap `length` for a real tokenizer count in production.
"""

from __future__ import annotations

import re
from dataclasses import dataclass, field
from typing import Callable, Dict, List, Optional, Sequence


@dataclass
class Chunk:
    text: str
    start: int  # character offset in the source document
    end: int
    metadata: Dict[str, str] = field(default_factory=dict)


def fixed_size_chunks(text: str, size: int = 2000, overlap: int = 200) -> List[Chunk]:
    """Split text into windows of `size` characters with `overlap` characters shared.

    Window boundaries are moved back to the nearest whitespace so words are not cut.
    """
    if size <= 0:
        raise ValueError("size must be positive")
    if not 0 <= overlap < size:
        raise ValueError("overlap must be >= 0 and smaller than size")
    chunks: List[Chunk] = []
    n = len(text)
    start = 0
    while start < n:
        end = min(start + size, n)
        if end < n:
            cut = text.rfind(" ", start + 1, end)
            if cut > start + size // 2:
                end = cut
        piece = text[start:end].strip()
        if piece:
            chunks.append(Chunk(piece, start, end))
        if end >= n:
            break
        next_start = end - overlap
        # snap forward to a word boundary so the overlap does not start mid-word
        if next_start > 0 and not text[next_start - 1].isspace():
            space = text.find(" ", next_start, end)
            if space != -1:
                next_start = space + 1
        start = max(next_start, start + 1)
    return chunks


DEFAULT_SEPARATORS: Sequence[str] = ("\n\n", "\n", ". ", " ")


def recursive_chunks(
    text: str,
    max_len: int = 2000,
    separators: Sequence[str] = DEFAULT_SEPARATORS,
    length: Callable[[str], int] = len,
) -> List[str]:
    """Split on the coarsest separator first, recursing into pieces that are too long,
    then greedily merge neighbouring pieces back up to `max_len`.

    This keeps paragraphs and sentences intact whenever they fit.
    """
    if length(text) <= max_len:
        return [text] if text.strip() else []
    if not separators:
        # hard split as a last resort
        return [text[i:i + max_len] for i in range(0, len(text), max_len)]
    sep, rest = separators[0], separators[1:]
    parts = text.split(sep)
    pieces: List[str] = []
    for i, part in enumerate(parts):
        # keep the separator attached so joining reproduces the original text
        segment = part + (sep if i < len(parts) - 1 else "")
        if length(segment) > max_len:
            pieces.extend(recursive_chunks(segment, max_len, rest, length))
        elif segment:
            pieces.append(segment)
    merged: List[str] = []
    buf = ""
    for p in pieces:
        if buf and length(buf + p) > max_len:
            merged.append(buf)
            buf = p
        else:
            buf += p
    if buf:
        merged.append(buf)
    return [m.strip() for m in merged if m.strip()]


_HEADING = re.compile(r"^(#{1,6})\s+(.*)$")


def markdown_chunks(md: str, max_len: int = 2000, source: Optional[str] = None) -> List[Chunk]:
    """Split Markdown on headings, keep the heading path as metadata, and
    sub-split long sections with `recursive_chunks`.

    Headings inside fenced code blocks are ignored.
    """
    sections: List[tuple] = []  # (heading_path, text, start_offset)
    path: List[str] = []
    buf: List[str] = []
    buf_start = 0
    offset = 0
    in_fence = False
    for line in md.splitlines(keepends=True):
        stripped = line.strip()
        if stripped.startswith("```") or stripped.startswith("~~~"):
            in_fence = not in_fence
        m = None if in_fence else _HEADING.match(line.rstrip("\n"))
        if m:
            if "".join(buf).strip():
                sections.append((" > ".join(path), "".join(buf), buf_start))
            level = len(m.group(1))
            path = path[: level - 1] + [m.group(2).strip()]
            buf = [line]
            buf_start = offset
        else:
            if not buf:
                buf_start = offset
            buf.append(line)
        offset += len(line)
    if "".join(buf).strip():
        sections.append((" > ".join(path), "".join(buf), buf_start))

    out: List[Chunk] = []
    for heading, body, start in sections:
        content_lines = [ln for ln in body.splitlines() if ln.strip()]
        if content_lines and all(_HEADING.match(ln) for ln in content_lines):
            continue  # heading with no body text: nothing useful to retrieve
        for piece in recursive_chunks(body, max_len):
            meta = {"heading": heading}
            if source:
                meta["source"] = source
            rel = body.find(piece)
            s = start + max(rel, 0)
            out.append(Chunk(piece, s, s + len(piece), meta))
    return out
