# -*- coding: utf-8 -*-
"""
道德经卷版合成器：81 章 → 17 卷 × 5 章（末卷 1 章）
====================================================
输入  daodejing.txt      （'# 一章'…'# 八十一章'，王弼本）
输出  daodejing_grouped.txt（'# 一卷'…'# 十七卷'；卷内原章名变 '@ ' 小节行，
                            渲染层居中——与飞鸟集"辑/首"同构）
原 daodejing.txt 保留为素材，不覆盖。
"""

from pathlib import Path

SRC = Path(__file__).parent
DEST = SRC / "daodejing_grouped.txt"
CHS_PER_JUAN = 5


def main():
    chapters, title, body = [], None, []
    for line in (SRC / "daodejing.txt").read_text(encoding="utf-8").splitlines():
        if line.startswith("# "):
            if title is not None:
                chapters.append((title, body))
            title, body = line[2:].strip(), []
        elif line.strip() and title is not None:
            body.append(line.strip())
    chapters.append((title, body))
    assert len(chapters) == 81, f"道德经应 81 章，实得 {len(chapters)}"

    out = ["《道德经》 王弼本（5 章一卷）", ""]
    n_juan = (81 + CHS_PER_JUAN - 1) // CHS_PER_JUAN
    for j in range(n_juan):
        lo, hi = j * CHS_PER_JUAN + 1, min((j + 1) * CHS_PER_JUAN, 81)
        # 章名 = 范围式（2026-08-29 用户拍板）：第1-5章 / 第81章
        out.append(f"# 第{lo}章" if lo == hi else f"# 第{lo}-{hi}章")
        for t, body in chapters[j * CHS_PER_JUAN:(j + 1) * CHS_PER_JUAN]:
            out.append(f"@ {t}")
            out += body
        out.append("")

    DEST.write_text("\n".join(out), encoding="utf-8")
    print(f"[OK] {DEST}：{n_juan} 卷 × {CHS_PER_JUAN} 章，共 81 章")


if __name__ == "__main__":
    main()
