#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""D05 资料检索页构建脚本（原文保真订正版）。

订正原则（workbuddy-repair-prompt）：
  - outputs/notes/*.md 必须与 inputs/notes/*.md 逐字节一致，禁止扩写；
    构建时强制校验，不一致直接报错退出。
  - 页面全文与搜索只对应原始笔记正文；
    类别、标题、出处从 inputs/索引.csv 读取。
  - 原始笔记没有 front matter，因此不再要求/解析 front matter。

从 notes/*.md（原始笔记的逐字节副本）与 ../inputs/索引.csv 生成：
  - 资料检索.html  单文件离线检索页（样式、数据、脚本全部内联）
  - data/notes.json 同一份数据的机器可读快照，供测试与复用

用法：
  python3 scripts/build.py
  python3 scripts/build.py --check    # 只做校验，不写文件

不访问网络，不读取本题目录之外的任何文件，不修改 inputs/。
"""

from __future__ import annotations

import argparse
import csv
import hashlib
import json
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
NOTES_DIR = ROOT / "notes"
SRC_DIR = ROOT / "src"
DATA_DIR = ROOT / "data"
OUTPUT_HTML = ROOT / "资料检索.html"
INPUTS_DIR = ROOT.parent / "inputs"
INDEX_CSV = INPUTS_DIR / "索引.csv"
INPUT_NOTES_DIR = INPUTS_DIR / "notes"

EXPECTED_IDS = [f"N{i:02d}" for i in range(1, 21)]
CATEGORY_ORDER = ["工作方法", "生活记录", "创作灵感", "学习笔记"]
TOKENS = ["__STYLE__", "__DATA_JSON__", "__SEARCH_CORE__", "__APP_JS__", "__TOTAL__"]


class BuildError(Exception):
    pass


def read_text_exact(path: Path) -> str:
    """按字节读入再解码，不经通用换行转换，保证与磁盘内容完全一致。"""
    try:
        raw = path.read_bytes()
    except FileNotFoundError as exc:
        raise BuildError(f"缺少文件：{path}") from exc
    try:
        return raw.decode("utf-8")
    except UnicodeDecodeError as exc:
        raise BuildError(f"{path.name}: 不是有效的 UTF-8 文本") from exc


def sha256_file(path: Path) -> str:
    return hashlib.sha256(path.read_bytes()).hexdigest()


def extract_heading(text: str, path: Path) -> str:
    """原始笔记的第一行 '# 标题' 即标题；没有则报错。"""
    for line in text.split("\n"):
        stripped = line.strip()
        if stripped.startswith("# "):
            return stripped[2:].strip()
        if stripped:
            break
    raise BuildError(f"{path.name}: 正文缺少一级标题")


def load_index() -> dict[str, dict[str, str]]:
    """读取 inputs/索引.csv：ID -> 标题/类别/文件/出处URL/备注。"""
    if not INDEX_CSV.is_file():
        raise BuildError(f"缺少索引文件：{INDEX_CSV}")
    with INDEX_CSV.open(encoding="utf-8-sig", newline="") as handle:
        rows = list(csv.DictReader(handle))
    if len(rows) != 20:
        raise BuildError(f"inputs/索引.csv 行数异常：{len(rows)}")
    index: dict[str, dict[str, str]] = {}
    for row in rows:
        note_id = row["ID"].strip()
        if note_id not in EXPECTED_IDS or note_id in index:
            raise BuildError(f"索引中 ID 异常或重复：{note_id!r}")
        for key in ("标题", "类别", "文件", "出处URL", "备注"):
            if not row.get(key, "").strip():
                raise BuildError(f"{note_id} 的索引字段 {key} 为空")
        index[note_id] = {key: row[key].strip() for key in ("标题", "类别", "文件", "出处URL", "备注")}
    if sorted(index) != EXPECTED_IDS:
        raise BuildError("索引 ID 必须为 N01–N20")
    return index


def load_notes(index: dict[str, dict[str, str]]) -> list[dict]:
    files = sorted(NOTES_DIR.glob("*.md"))
    if len(files) != 20:
        raise BuildError(f"notes/ 中应有 20 个 .md 文件，实际 {len(files)} 个")

    notes: list[dict] = []
    for path in files:
        text = read_text_exact(path)
        if not text.strip():
            raise BuildError(f"{path.name}: 正文为空")

        # 保真闸门：outputs/notes 必须与 inputs/notes 逐字节一致，禁止扩写。
        original = INPUT_NOTES_DIR / path.name
        if not original.is_file():
            raise BuildError(f"缺少原始笔记：{original}")
        if path.read_bytes() != original.read_bytes():
            raise BuildError(
                f"{path.name} 与 inputs/notes/{path.name} 不逐字节一致（禁止扩写），"
                "请用原始文件覆盖 outputs/notes/ 后重新构建"
            )

        # 从文件名推出 ID（notes/01.md -> N01），与索引对应。
        note_id = "N" + path.stem
        meta = index.get(note_id)
        if meta is None:
            raise BuildError(f"{path.name} 在 inputs/索引.csv 中没有对应条目")

        title = extract_heading(text, path)
        if title != meta["标题"]:
            raise BuildError(
                f"{note_id} 标题与索引不一致：笔记 {title!r} != 索引 {meta['标题']!r}"
            )
        if meta["文件"] != f"notes/{path.name}":
            raise BuildError(
                f"{note_id} 文件名与索引不一致：notes/{path.name} != {meta['文件']}"
            )
        if meta["类别"] not in CATEGORY_ORDER:
            raise BuildError(f"{note_id}: 未知类别 {meta['类别']!r}")

        # 原始笔记没有标签列，保持为空，不得扩写。
        notes.append(
            {
                "id": note_id,
                "title": meta["标题"],
                # 原始笔记没有副标题/标签/摘要，保持为空，不得扩写。
                "subtitle": "",
                "category": meta["类别"],
                "tags": [],
                "source": meta["出处URL"],
                "sourceNote": meta["备注"],
                "summary": "",
                # body 即原始笔记全文（逐字节一致）。
                "body": text,
                "file": f"notes/{path.name}",
            }
        )

    notes.sort(key=lambda item: item["id"])
    ids = [note["id"] for note in notes]
    if ids != EXPECTED_IDS:
        raise BuildError(f"ID 必须为 N01–N20，实际为 {ids}")

    counts: dict[str, int] = {}
    for note in notes:
        counts[note["category"]] = counts.get(note["category"], 0) + 1
    expected_counts = {name: 5 for name in CATEGORY_ORDER}
    if counts != expected_counts:
        raise BuildError(f"每个类别应有 5 篇，实际为 {counts}")

    return notes


def build_data(notes: list[dict]) -> dict:
    counts: dict[str, int] = {}
    for note in notes:
        counts[note["category"]] = counts.get(note["category"], 0) + 1
    return {
        "schema": 2,
        "total": len(notes),
        "categories": [
            {"name": name, "count": counts[name]} for name in CATEGORY_ORDER
        ],
        "notes": notes,
    }


def escape_json_for_html(payload: str) -> str:
    """把 JSON 中可能闭合 script 的字符转成 Unicode 转义，textContent 读回后仍是原文。"""
    escaped = (
        payload.replace("&", "\\u0026")
        .replace("<", "\\u003c")
        .replace(">", "\\u003e")
        .replace("\u2028", "\\u2028")
        .replace("\u2029", "\\u2029")
    )
    if "</script" in escaped.lower():
        raise BuildError("JSON 中仍存在 </script 序列")
    return escaped


def render_html(notes: list[dict], data: dict) -> str:
    template = read_text_exact(SRC_DIR / "template.html")
    css = read_text_exact(SRC_DIR / "style.css").strip()
    search_core = read_text_exact(SRC_DIR / "search-core.js").strip()
    app_js = read_text_exact(SRC_DIR / "app.js").strip()
    payload = json.dumps(data, ensure_ascii=False, separators=(",", ":"))
    embedded_json = escape_json_for_html(payload)

    for script_name, script in (("search-core.js", search_core), ("app.js", app_js)):
        if "</script" in script.lower():
            raise BuildError(f"{script_name} 含有 </script 序列，无法内联")

    html = template
    html = html.replace("/*__STYLE__*/", css)
    html = html.replace("__DATA_JSON__", embedded_json)
    html = html.replace("/*__SEARCH_CORE__*/", search_core)
    html = html.replace("/*__APP_JS__*/", app_js)
    html = html.replace("__TOTAL__", str(len(notes)))

    leftovers = [token for token in TOKENS if token in html]
    if leftovers:
        raise BuildError(f"模板占位符未替换：{leftovers}")

    expected_links = {note["file"] for note in notes}
    if 'noteLink.href = note.file;' not in app_js:
        raise BuildError("app.js 未把原始笔记路径写入链接")
    if 'href="notes/01.md"' not in html:
        raise BuildError("模板缺少原始笔记链接兜底")
    for link in expected_links:
        if not (ROOT / link).is_file():
            raise BuildError(f"原始笔记不存在：{ROOT / link}")

    # 保真：页面全文必须对应原始笔记（以 N07/N12 特殊内容为哨兵）。
    if "蓝鲸回形针" not in notes[11]["body"]:
        raise BuildError("N12 原始正文缺少检索专用词 蓝鲸回形针")
    if '<img src=x onerror="alert(1)">' not in notes[6]["body"]:
        raise BuildError("N07 原始正文缺少安全演示文字")
    return html


def main() -> int:
    parser = argparse.ArgumentParser(description="构建 D05 离线资料检索页（原文保真订正版）")
    parser.add_argument("--check", action="store_true", help="只校验，不写入文件")
    args = parser.parse_args()

    try:
        index = load_index()
        notes = load_notes(index)
        data = build_data(notes)
        html = render_html(notes, data)
    except BuildError as exc:
        print(f"[FAIL] {exc}", file=sys.stderr)
        return 1

    if args.check:
        print(f"[OK] 校验通过：{len(notes)} 篇原始笔记（逐字节保真），HTML {len(html):,} 字符")
        return 0

    DATA_DIR.mkdir(parents=True, exist_ok=True)
    OUTPUT_HTML.write_text(html, encoding="utf-8", newline="")
    data_path = DATA_DIR / "notes.json"
    data_path.write_text(
        json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8", newline=""
    )

    digest = hashlib.sha256(html.encode("utf-8")).hexdigest()[:16]
    print(f"[OK] 已生成 {OUTPUT_HTML.relative_to(ROOT)}")
    print(f"     笔记 {len(notes)} 篇（与 inputs/notes 逐字节一致），类别 {len(data['categories'])} 个，大小 {len(html.encode('utf-8')):,} 字节")
    print(f"     数据 {data_path.relative_to(ROOT)}，HTML SHA-256 前 16 位 {digest}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
