"""Heading-aware chunking of Markdown for embedding or long-context prompts."""

from __future__ import annotations

import re
from typing import Dict, List

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


def estimate_tokens(text: str) -> int:
    """Rough estimate: about 4 characters per token for English. Use a real tokenizer for billing."""
    return max(1, len(text) // 4) if text else 0


def chunk_markdown(md: str, max_tokens: int = 500, url: str = "") -> List[Dict[str, str]]:
    """Split by headings; split oversized sections on blank lines; never split inside code fences.
    Each chunk carries its heading path so it stays understandable on its own."""
    sections, path, buf, in_code = [], [], [], False
    for line in md.splitlines():
        if line.strip().startswith("```"):
            in_code = not in_code
        m = None if in_code else _H.match(line)
        if m:
            if "".join(buf).strip():
                sections.append((list(path), "\n".join(buf).strip()))
            level = len(m.group(1))
            path = path[: level - 1] + [m.group(2).strip()]
            buf = []
        else:
            buf.append(line)
    if "".join(buf).strip():
        sections.append((list(path), "\n".join(buf).strip()))

    chunks = []
    for hp, body in sections:
        header = " > ".join(hp)
        blocks, cur, in_code = [], [], False
        for line in body.split("\n"):
            if line.strip().startswith("```"):
                in_code = not in_code
            if not line.strip() and not in_code and cur:
                blocks.append("\n".join(cur))
                cur = []
            elif line.strip() or in_code:
                cur.append(line)
        if cur:
            blocks.append("\n".join(cur))
        piece = []
        for b in blocks:
            if piece and estimate_tokens("\n\n".join(piece + [b])) > max_tokens:
                chunks.append({"heading": header, "text": "\n\n".join(piece), "url": url})
                piece = []
            piece.append(b)
        if piece:
            chunks.append({"heading": header, "text": "\n\n".join(piece), "url": url})
    return chunks
