# -*- coding: utf-8 -*-
"""merge_book.py —— 把 tutorial/ 下各章按顺序合并为 book.md（全书单文件）。

用法：python code/merge_book.py
输出：book.md（项目根目录，供 pandoc 转 PDF/HTML）
"""
import os
import re

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TUT = os.path.join(ROOT, "tutorial")

# 章节顺序（00 导读 → 16 排错 → 附录 A/B/C）
CHAPTERS = [
    "00-导读与学习路线.md",
    "01-肿瘤微环境与细胞通讯的生物学基础.md",
    "02-空间转录组技术原理.md",
    "03-生信入门必备.md",
    "04-空间生态位与通讯推断方法学总览.md",
    "05-课题设计.md",
    "06-环境搭建与工具链.md",
    "07-数据获取.md",
    "08-预处理与质控.md",
    "09-降维聚类与细胞类型注释.md",
    "10-空间生态位识别.md",
    "11-细胞通讯分析基础-CellChat.md",
    "12-生态位内细胞通讯分析.md",
    "13-通讯重编程-生态位间差异分析.md",
    "14-论文级图表与可视化.md",
    "15-结果解读与论文写作.md",
    "16-常见问题与排错.md",
    "附录A-术语表.md",
    "附录B-资源与参考文献.md",
    "附录C-示例数据与代码清单.md",
]


def main():
    parts = []
    missing = []
    for name in CHAPTERS:
        path = os.path.join(TUT, name)
        if not os.path.exists(path):
            missing.append(name)
            continue
        with open(path, encoding="utf-8") as f:
            content = f.read().strip()
        parts.append(content)
    if missing:
        print("警告：缺少章节文件：", missing)
    book = "\n\n\\newpage\n\n".join(parts)
    # 清理：连续多个空行 → 一个
    book = re.sub(r"\n{3,}", "\n\n", book)
    out = os.path.join(ROOT, "book.md")
    with open(out, "w", encoding="utf-8") as f:
        f.write(book + "\n")
    print(f"合并完成：{len(parts)} 章 → {out}（{len(book)/1024:.1f} KB）")
    if missing:
        raise SystemExit(1)


if __name__ == "__main__":
    main()
