# -*- coding: utf-8 -*-
"""把 v3（48 页扩充版）分片组装为第 2 章主讲稿，并做完整性/密度校验。
用法：python3 _assemble_v3.py [--check]
分片顺序：ch2b-head + p1a + p1b + p2a + p2b + p3a + p3b + ch2b-tail
"""
import os, re, sys, shutil

HERE = os.path.dirname(os.path.abspath(__file__))
P = os.path.join(HERE, '_parts2')
FINAL = os.path.join(HERE, '第2章-软件项目启动-讲稿.md')
ARCHIVE_DIR = os.path.join(HERE, '_v2-28页版')
PARTS = ['ch2b-head.md', 'ch2b-p1a.md', 'ch2b-p1b.md', 'ch2b-p2a.md',
         'ch2b-p2b.md', 'ch2b-p3a.md', 'ch2b-p3b.md', 'ch2b-tail.md']
ANCHOR = re.compile(r'^###\s+【(\d+)\.(\d+)(?:\s*[–\-—]\s*\d+\.(\d+))?】\s*(.*)$', re.M)
PAGES, MIN_PER_PAGE, MIN_TOTAL = 48, 400, 36000


def han(s):
    return len(re.sub(r'[^\u4e00-\u9fff]', '', s))


def main():
    check_only = '--check' in sys.argv
    missing = [p for p in PARTS if not os.path.isfile(os.path.join(P, p))]
    if missing:
        print('❌ 缺少分片:', missing); return 1
    md = '\n'.join(
        '\n'.join(l for l in open(os.path.join(P, p), encoding='utf-8').read().split('\n')
                  if not l.lstrip().startswith('<!--')).rstrip() + '\n'
        for p in PARTS)
    ms = list(ANCHOR.finditer(md))
    nums, spoken = [], []
    for i, m in enumerate(ms):
        body = md[m.start():(ms[i + 1].start() if i + 1 < len(ms) else len(md))]
        nums.append(int(m.group(2)))
        spoken.append(sum(han(l) for l in body.split('\n') if l.strip().startswith('>')))
    total = sum(spoken)
    ok_num = sorted(nums) == list(range(1, PAGES + 1))
    thin = [(n, w) for n, w in zip(nums, spoken) if w < MIN_PER_PAGE]
    star = [15, 18, 19, 21, 33, 35, 41, 45]
    in_class = sum(w for n, w in zip(nums, spoken) if n not in star)
    print(f"锚点 {len(ms)} 个 ｜ 页码 1–{PAGES} 连续无重复: {'✅' if ok_num else '❌'}")
    print(f"口播合计 {total} 字（≈{total / 240:.0f} 分钟）｜ 上课 40 页 {in_class} 字（≈{in_class / 240:.0f} 分钟）｜ ★课后 8 页 {total - in_class} 字")
    print(f"每页口播 ≥{MIN_PER_PAGE} 字: {'✅ 全部达标' if not thin else '⚠ ' + str(thin)}")
    print(f"总字数 ≥{MIN_TOTAL}: {'✅' if total >= MIN_TOTAL else '❌'}")
    if not (ok_num and not thin and total >= MIN_TOTAL):
        print('\n⛔ 校验未通过，未写文件。'); return 1
    if check_only:
        print('\n✅ 校验通过（--check：未写文件）'); return 0
    os.makedirs(ARCHIVE_DIR, exist_ok=True)
    if os.path.isfile(FINAL):
        shutil.copy2(FINAL, os.path.join(ARCHIVE_DIR, '第2章-软件项目启动-讲稿（28页v2版）.md'))
        print('📦 旧版（28 页 v2）已归档 →', os.path.join(ARCHIVE_DIR, '第2章-软件项目启动-讲稿（28页v2版）.md'))
    with open(FINAL, 'w', encoding='utf-8') as f:
        f.write(md)
    print(f"📄 已生成 {os.path.basename(FINAL)}：{len(md.encode('utf-8')) / 1024:.0f} KB ｜ {len(ms)} 页锚点 ｜ 口播 {total} 字")
    print('\n✅ v3 组装完成 → 下一步：cd ../备课台 && python3 _build_prep.py')
    return 0


if __name__ == '__main__':
    sys.exit(main())
