"""实例「系统说明」:加载 Markdown,生成 h2 目录与带锚点正文."""
from __future__ import annotations

import re
from functools import lru_cache
from html import escape
from pathlib import Path
from typing import Any

from lib.hub.hub_strategy_lib import render_markdown_html
from lib.paths import REPO_ROOT


def system_guide_md_path() -> Path:
    return REPO_ROOT / "docs" / "系统说明.md"


def _slugify(text: str) -> str:
    raw = re.sub(r"<[^>]+>", "", text or "")
    raw = re.sub(r"\s+", "-", raw.strip())
    raw = re.sub(r"[^\w\u4e00-\u9fff\-]+", "", raw)
    return raw[:80] or "section"


def _inject_h2_ids(html: str) -> tuple[str, list[dict[str, str]]]:
    """为 h2 注入 id,并收集目录(仅 h2)."""
    toc: list[dict[str, str]] = []
    used: dict[str, int] = {}

    def repl(m: re.Match[str]) -> str:
        inner = m.group(1)
        base = _slugify(inner)
        n = used.get(base, 0) + 1
        used[base] = n
        hid = base if n == 1 else f"{base}-{n}"
        toc.append({"id": hid, "title": re.sub(r"<[^>]+>", "", inner).strip()})
        return f'<h2 id="{escape(hid)}">{inner}</h2>'

    out = re.sub(r"<h2>(.*?)</h2>", repl, html, flags=re.I | re.S)
    return out, toc


@lru_cache(maxsize=4)
def _load_payload_cached(mtime_ns: int, path_str: str) -> dict[str, Any]:
    path = Path(path_str)
    try:
        md_text = path.read_text(encoding="utf-8")
    except OSError:
        md_text = "# 系统说明缺失\n\n未找到 `docs/系统说明.md`。"
    body = render_markdown_html(md_text)
    body, toc = _inject_h2_ids(body)
    return {"html": body, "toc": toc, "mtime_ns": mtime_ns}


def load_system_guide_payload() -> dict[str, Any]:
    path = system_guide_md_path()
    try:
        mtime_ns = path.stat().st_mtime_ns
    except OSError:
        mtime_ns = 0
    return dict(_load_payload_cached(mtime_ns, str(path)))


def system_guide_template_context() -> dict[str, Any]:
    payload = load_system_guide_payload()
    return {
        "system_guide_html": payload.get("html") or "",
        "system_guide_toc": payload.get("toc") or [],
    }
