"""Vault MD 按 ## heading 分块。"""

from __future__ import annotations

import re
from typing import Any

_HEADING_RE = re.compile(r"^##\s+(.+?)\s*$", re.MULTILINE)


def split_md_by_heading(body: str) -> list[dict[str, Any]]:
    """将 markdown body 按二级标题切成 chunk 列表。"""
    text = str(body or "")
    if not text.strip():
        return []

    matches = list(_HEADING_RE.finditer(text))
    if not matches:
        return [{"heading": "", "text": text.strip(), "index": 0}]

    chunks: list[dict[str, Any]] = []
    if matches[0].start() > 0:
        preamble = text[: matches[0].start()].strip()
        if preamble:
            chunks.append({"heading": "", "text": preamble, "index": 0})

    for i, match in enumerate(matches):
        start = match.end()
        end = matches[i + 1].start() if i + 1 < len(matches) else len(text)
        section = text[start:end].strip()
        chunks.append(
            {
                "heading": match.group(1).strip(),
                "text": section,
                "index": len(chunks),
            }
        )
    return chunks


def best_chunk_for_query(chunks: list[dict[str, Any]], query: str) -> dict[str, Any] | None:
    """按 query 与 heading/text 词面匹配选最佳 chunk。"""
    if not chunks:
        return None
    q = query.lower()
    if not q.strip():
        return chunks[0]

    best: dict[str, Any] | None = None
    best_score = -1.0
    for chunk in chunks:
        heading = str(chunk.get("heading") or "").lower()
        body = str(chunk.get("text") or "").lower()
        hay = f"{heading} {body}"
        hits = sum(1 for token in q.split() if len(token) > 1 and token.lower() in hay)
        score = hits / max(1, len(q.split()))
        if heading and any(t in heading for t in q.split() if len(t) > 1):
            score += 0.5
        if score > best_score:
            best_score = score
            best = chunk
    return best or chunks[0]
