# -*- coding: utf-8 -*-
"""组装第 3 / 4 次课讲稿（并与课件逐页校验）。
用法：python3 _assemble_34.py [--check]
产出：
  讲稿/第3次课-第3章-采购管理（一）-讲稿.md   （44 页锚点）
  讲稿/第4次课-第3章-采购管理（二）-讲稿.md   （42 页锚点）
"""
import os, re, sys, shutil

HERE = os.path.dirname(os.path.abspath(__file__))     # …/讲稿
P = os.path.join(HERE, '_parts34')
JOBS = [
    dict(no=3, total=44, out='第3次课-第3章-采购管理（一）-讲稿.md',
         parts=['l3-head.md', 'l3-p1.md', 'l3-p2.md', 'l3-p3.md', 'l3-tail.md']),
    dict(no=4, total=42, out='第4次课-第3章-采购管理（二）-讲稿.md',
         parts=['l4-head.md', 'l4-p1.md', 'l4-p2.md', 'l4-p3.md', 'l4-tail.md']),
]
ANCHOR = re.compile(r'^###\s+【(\d+)\.(\d+)】\s*(.*)$', re.M)
MIN_PER_PAGE, MIN_TOTAL = 250, 20000


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


def main():
    check_only = '--check' in sys.argv
    ok_all = True
    for job in JOBS:
        miss = [p for p in job['parts'] if not os.path.isfile(os.path.join(P, p))]
        if miss:
            print(f"⏳ 第 {job['no']} 次课缺分片：{miss}"); ok_all = False; continue
        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 job['parts'])
        ms = list(ANCHOR.finditer(md))
        bad_no = [m.group(1) for m in ms if int(m.group(1)) != job['no']]
        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, job['total'] + 1)) and not bad_no
        thin = [(n, w) for n, w in zip(nums, spoken) if w < MIN_PER_PAGE]
        star = {3: {12, 17, 26, 33, 36, 42}, 4: {9, 26, 27, 28, 31, 33}}[job['no']]
        in_class = sum(w for n, w in zip(nums, spoken) if n not in star)
        print(f"【第 {job['no']} 次课】锚点 {len(ms)} 个 ｜ 页码 1–{job['total']} 连续且前缀正确: {'✅' if ok_num else '❌' + str(nums[:5])}")
        print(f"   口播合计 {total} 字（≈{total/240:.0f} 分钟）｜ 上课页 {in_class} 字（≈{in_class/240:.0f} 分钟）｜ ★课后 {total-in_class} 字")
        print(f"   每页口播 ≥{MIN_PER_PAGE}: {'✅ 全部达标' if not thin else '⚠ ' + str(thin)} ｜ 总字数 ≥{MIN_TOTAL}: {'✅' if total >= MIN_TOTAL else '❌'}")
        if not (ok_num and not thin and total >= MIN_TOTAL):
            ok_all = False; print('   ⛔ 校验未通过，未写文件'); continue
        if check_only:
            continue
        out = os.path.join(HERE, job['out'])
        with open(out, 'w', encoding='utf-8') as f:
            f.write(md)
        print(f"   📄 已生成 {job['out']}：{len(md.encode('utf-8'))/1024:.0f} KB ｜ {len(ms)} 页锚点 ｜ 口播 {total} 字")
    if not check_only and ok_all:
        print('\n✅ 组装完成 → 下一步：cd ../备课台 && python3 _build_prep.py')
    return 0 if ok_all else 1


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