# -*- coding: utf-8 -*-
"""组装第 16 次课讲稿（并与课件逐页校验）。
用法：python3 _assemble_12.py [--check]
产出：讲稿/第12次课-第7章-质量管理-讲稿.md（32 页锚点）
分片：_parts16/l12-head.md、l12-p1..p3.md、l12-tail.md
"""
import os, re, sys

HERE = os.path.dirname(os.path.abspath(__file__))     # …/讲稿
P = os.path.join(HERE, '_parts16')
JOBS = [
    dict(no=16, total=34, out='第16次课-综合案例与整合管理-讲稿.md',
         parts=['l16-head.md', 'l16-p1.md', 'l16-p2.md', 'l16-p3.md', 'l16-tail.md']),
]
ANCHOR = re.compile(r'^###\s+【(\d+)\.(\d+)】\s*(.*)$', re.M)
MIN_PER_PAGE, MIN_TOTAL = 250, 8000   # 单讲口径（第 6 章两讲分别约 1.4 万 / 1.1 万字）
STAR = {16: set()}
# 锚点标题须与课件页面标题一致（软校验：完全一致率）
TITLES = None


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


def load_titles():
    """从课件内容模块读页面标题，用于校验锚点标题逐字一致。"""
    cw = os.path.join(HERE, '..', '课件成品-HTML', '软件项目管理-16周课件')
    if not os.path.isdir(cw):
        return {}
    sys.path.insert(0, os.path.abspath(cw))
    try:
        os.chdir(cw)
        import importlib
        import _content16a as a, _content16b as b, _content16c as c
        L = a.SLIDES_16A + b.SLIDES_16B + c.SLIDES_16C
        return {16: [t for (_p, t, _b) in L]}
    except Exception as e:
        print('⚠ 课件标题读取失败（跳过标题一致性校验）:', e)
        return {}
    finally:
        os.chdir(HERE)


def main():
    check_only = '--check' in sys.argv
    titles = load_titles()
    ok_all = True
    for job in JOBS:
        no, total = job['no'], job['total']
        miss = [p for p in job['parts'] if not os.path.isfile(os.path.join(P, p))]
        if miss:
            print(f"⏳ 第 {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)) != no]
        nums, spoken, tits = [], [], []
        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)))
            # 锚点标题可能带「（X 分钟）」时长后缀，比较时剥掉
            tits.append(re.sub(r'（[^）]*分钟）\s*$', '', m.group(3).strip()))
            spoken.append(sum(han(l) for l in body.split('\n') if l.strip().startswith('>')))
        total_han = sum(spoken)
        ok_num = sorted(nums) == list(range(1, total + 1)) and not bad_no
        thin = [(n, w) for n, w in zip(nums, spoken) if w < MIN_PER_PAGE]
        star = STAR[no]
        in_class = sum(w for n, w in zip(nums, spoken) if n not in star)
        print(f"【第 {no} 次课】锚点 {len(ms)} 个 ｜ 页码 1–{total} 连续且前缀正确: {'✅' if ok_num else '❌ ' + str(nums[:5])}")
        print(f"   口播合计 {total_han} 字（≈{total_han/240:.0f} 分钟）｜ 上课页 {in_class} 字（≈{in_class/240:.0f} 分钟）｜ ★课后 {total_han-in_class} 字")
        print(f"   每页口播 ≥{MIN_PER_PAGE}: {'✅ 全部达标' if not thin else '⚠ ' + str(thin)} ｜ 总字数 ≥{MIN_TOTAL}: {'✅' if total_han >= MIN_TOTAL else '❌'}")
        if titles.get(no):
            ref = titles[no]
            bad_title = [(n, t, ref[n-1]) for n, t in zip(nums, tits) if n <= len(ref) and t != ref[n-1]]
            print(f"   标题与课件逐字一致: {'✅ ' + str(len(ref)) + ' 页全部一致' if not bad_title else '⚠ ' + str(len(bad_title)) + ' 页不一致'}")
            for n, t, r in bad_title[:5]:
                print(f"      · {no}.{n} 讲稿「{t}」 ≠ 课件「{r}」")
        if not (ok_num and not thin and total_han >= 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_han} 字")
    if not check_only and ok_all:
        print('\n✅ 组装完成 → 下一步：cd ../备课台 && python3 _build_prep.py；再跑 _make_pdf.py 生成打印版')
    return 0 if ok_all else 1


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