# -*- coding: utf-8 -*-
"""
生成 PDF 书籍源文件：合并 tutorial/ 全部章节 → build/book.md
处理：
  1. 章节/小节标题加 {.unnumbered}（保留手动编号，交叉引用一致）
  2. 图片路径 ../figures/ → figures/（相对 pandoc 运行目录）
  3. 生成书籍级 frontmatter（书名页信息由 preamble.tex 封面承担）
  4. 代码块内的 # 注释行不受影响（pandoc 原生识别 fenced code）
"""
import io
import os
import re
import glob

OUT_DIR = "build"
os.makedirs(OUT_DIR, exist_ok=True)

# 章节顺序（00 导读 → 15 附录）
ORDER = [
    "00-导读与学习路线.md",
    "01-细胞生物学知识补充.md",
    "02-生物信息学知识补充.md",
    "03-公共数据库详解.md",
    "04-课题设计与选题.md",
    "05-环境搭建与工具链.md",
    "06-数据获取.md",
    "07-差异表达分析.md",
    "08-可视化与图表.md",
    "09-功能富集分析.md",
    "10-PPI网络与hub基因.md",
    "11-生存分析与预后模型.md",
    "12-独立验证与拓展.md",
    "13-论文写作与发表.md",
    "14-常见问题与排错.md",
    "15-附录-术语表与资源.md",
]

HEADING_RE = re.compile(r"^(#{1,3})\s+(.+?)\s*$")


def process_heading(line):
    """给标题加 {.unnumbered}（若还没有）；代码块外才调用"""
    m = HEADING_RE.match(line.rstrip())
    if not m:
        return line
    level, text = m.group(1), m.group(2)
    # 去掉行尾可能已有的属性
    text = re.sub(r"\s*\{[^}]*\}\s*$", "", text)
    return f"{level} {text} {{.unnumbered}}"


def process_file(path):
    """逐行处理单个章节文件：代码块状态机 + 标题 unnumbered + 图路径 + emoji 替换"""
    lines = io.open(path, encoding="utf-8").read().split("\n")
    out = []
    in_code = False
    for line in lines:
        stripped = line.strip()
        # 代码块开关：``` 或 ```r 等
        if stripped.startswith("```"):
            in_code = not in_code
            out.append(line)
            continue
        if in_code:
            # 代码块内：只处理图片路径（不处理标题）
            out.append(line.replace("../figures/", "figures/"))
            continue
        # 正文：处理标题
        line = process_heading(line)
        # 图片路径
        line = line.replace("../figures/", "figures/")
        # emoji → 文字（中文字体不含 emoji，PDF 会缺字）
        line = line.replace("✅", "（是）").replace("❌", "（否）")
        # ↔ 双向箭头（SimSun 缺失）→ 文字
        line = line.replace("↔", "与")
        out.append(line)
    return "\n".join(out)


def main():
    parts = []
    for name in ORDER:
        path = os.path.join("tutorial", name)
        if not os.path.exists(path):
            print("WARN missing:", path)
            continue
        content = process_file(path)
        # 章节之间用 --- 分隔（pandoc 渲染为水平线，保持章节块清晰）
        parts.append(content)

    book = "\n\n---\n\n".join(parts) + "\n"

    out_path = os.path.join(OUT_DIR, "book.md")
    with io.open(out_path, "w", encoding="utf-8", newline="\n") as fh:
        fh.write(book)

    # 统计
    n_unnum = len(re.findall(r"\{\.unnumbered\}", book))
    n_figs = len(re.findall(r"!\[[^\]]*\]\(figures/fig\d+_", book))
    n_code = len(re.findall(r"^```", book, re.M)) // 2
    print(f"book.md 生成: {out_path}  ({os.path.getsize(out_path)/1024:.0f} KB)")
    print(f"unnumbered 标题: {n_unnum} | 图引用: {n_figs} | 代码块: {n_code}")


def postprocess_tex(tex_path):
    """后处理 book.tex：删除 section/subsection 级目录条目（目录只保留章级）"""
    with io.open(tex_path, encoding="utf-8") as fh:
        tex = fh.read()
    # 删除 pandoc 为 section/subsection/subsubsection 生成的 addcontentsline
    tex = re.sub(r"\\addcontentsline\{toc\}\{(section|subsection|subsubsection)\}\{[^}]*\}\n?", "", tex)
    with io.open(tex_path, "w", encoding="utf-8", newline="\n") as fh:
        fh.write(tex)
    n = len(re.findall(r"\\addcontentsline\{toc\}\{chapter\}", tex))
    print(f"book.tex 后处理完成：目录仅保留 {n} 条章级条目")


if __name__ == "__main__":
    main()
