"""中控「使用说明」:读取 manual_trading_hub/docs/help 下的 MD."""

from __future__ import annotations

from pathlib import Path
from typing import Any

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

HELP_SECTIONS: tuple[dict[str, str], ...] = (
    {"key": "quickstart", "label": "快速开始", "title": "快速开始", "md_file": "01-quickstart.md"},
    {"key": "hub-nav", "label": "中控导航", "title": "中控导航说明", "md_file": "02-hub-nav.md"},
    {"key": "monitor", "label": "监控区", "title": "监控区与实例入口", "md_file": "03-monitor.md"},
    {"key": "instance", "label": "实例页面", "title": "实例页导航说明", "md_file": "04-instance.md"},
    {"key": "settings", "label": "设置说明", "title": "设置与配置说明", "md_file": "05-settings.md"},
)


def _help_dir() -> Path:
    return REPO_ROOT / "manual_trading_hub" / "docs" / "help"


def _section_meta(key: str) -> dict[str, str]:
    k = (key or "").strip().lower()
    for item in HELP_SECTIONS:
        if item["key"] == k:
            return item
    raise KeyError(key)


def _md_path(section_key: str) -> Path:
    return _help_dir() / _section_meta(section_key)["md_file"]


def help_meta_payload() -> dict[str, Any]:
    sections = [{"key": s["key"], "label": s["label"], "title": s["title"]} for s in HELP_SECTIONS]
    return {"ok": True, "sections": sections}


def load_help_payload(section_key: str) -> dict[str, Any]:
    key = (section_key or "").strip().lower()
    meta = _section_meta(key)
    md_path = _md_path(key)
    md_text = md_path.read_text(encoding="utf-8") if md_path.is_file() else ""
    return {
        "ok": True,
        "section_key": key,
        "label": meta["label"],
        "title": meta["title"],
        "md_source": str(md_path.relative_to(REPO_ROOT)).replace("\\", "/"),
        "content_html": render_markdown_html(md_text),
    }
