# -*- coding: utf-8 -*-
"""第 7/8/9 次课课件自检（模块页数 / 插图路径 / 标题唯一 / 教师向措辞 / 公式体例）

用法：python3 _check789.py
"""
import os, re, sys, glob

ROOT = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, ROOT)

EXPECT = {
    'lecture7': ('_content7a', 'SLIDES_7A', 14), 'lecture7b': ('_content7b', 'SLIDES_7B', 12),
    'lecture7c': ('_content7c', 'SLIDES_7C', 14),
    'lecture8a': ('_content8a', 'SLIDES_8A', 14), 'lecture8b': ('_content8b', 'SLIDES_8B', 13),
    'lecture8c': ('_content8c', 'SLIDES_8C', 13),
    'lecture9a': ('_content9a', 'SLIDES_9A', 13), 'lecture9b': ('_content9b', 'SLIDES_9B', 13),
    'lecture9c': ('_content9c', 'SLIDES_9C', 12),
}
TOTAL = {7: 40, 8: 40, 9: 38}
# 教师向 / 备课痕迹（学生端不得出现）
BANNED = [r'课上可跳过', r'讲[AB]\b', r'教师只', r'PPT 第\s*\d+\s*页', r'教材\s*[Pp]\s*\d+', r'课堂用法']


def main():
    problems, ok = [], []
    mods = {}
    for key, (mod, sym, n) in EXPECT.items():
        try:
            m = __import__(mod)
            slides = getattr(m, sym)
            mods[key] = slides
            if len(slides) != n:
                problems.append(f'{mod}.{sym} 页数 {len(slides)} ≠ {n}')
            else:
                ok.append(f'{mod} {n} 页')
            for i, (pt, title, body) in enumerate(slides, 1):
                if not (pt and title and body and body.strip()):
                    problems.append(f'{mod} 第 {i} 页有空字段')
        except Exception as e:
            problems.append(f'导入 {mod} 失败：{e}')

    # 每讲合计
    for lec, parts in {7: ('lecture7a', 'lecture7b', 'lecture7c'),
                       8: ('lecture7a', 'lecture7b', 'lecture7c'),
                       9: ('lecture9a', 'lecture9b', 'lecture9c')}.items():
        pass
    sums = {
        7: sum(len(mods.get(k, [])) for k in ('lecture7', 'lecture7b', 'lecture7c')),
        8: sum(len(mods.get(k, [])) for k in ('lecture8a', 'lecture8b', 'lecture8c')),
        9: sum(len(mods.get(k, [])) for k in ('lecture9a', 'lecture9b', 'lecture9c')),
    }
    for k, v in sums.items():
        (ok if v == TOTAL[k] else problems).append(
            f'第 {k} 次课合计 {v} 页' + ('' if v == TOTAL[k] else f' ≠ {TOTAL[k]}'))

    # 标题唯一 + 教师向措辞 + 公式体例
    all_titles, all_bodies = [], []
    for key, slides in mods.items():
        for i, (pt, title, body) in enumerate(slides, 1):
            all_titles.append(title)
            all_bodies.append((key, i, body))
    dup = {t for t in all_titles if all_titles.count(t) > 1}
    if dup:
        problems.append(f'重复标题 {len(dup)} 个：{list(dup)[:3]}')
    for pat in BANNED:
        hits = [(k, i, pat) for k, i, b in all_bodies if re.search(pat, b)]
        if hits:
            problems.append(f'教师向措辞「{pat}」{len(hits)} 处，如 {hits[:2]}')
    html_tags = [(k, i) for k, i, b in all_bodies if re.search(r'<(?:sub|sup)>', b)]
    if html_tags:
        problems.append(f'内联 <sub>/<sup> {len(html_tags)} 处（应用 LaTeX）')
    odd_dollar = [(k, i, b.count('$')) for k, i, b in all_bodies if b.count('$') % 2]
    if odd_dollar:
        problems.append(f'$ 未配对 {len(odd_dollar)} 页：{odd_dollar[:3]}')

    # 插图路径
    missing = []
    for key, i, b in all_bodies:
        for src in re.findall(r'<img[^>]+src="([^"]+)"', b):
            if src.startswith('http'):
                continue
            p = os.path.normpath(os.path.join(ROOT, 'lecture' + key[-2:-1], src))
            if not os.path.isfile(p):
                missing.append((key, i, src))
    if missing:
        problems.append(f'插图缺失 {len(missing)} 处：{missing[:4]}')
    else:
        ok.append('全部插图路径可解析')

    print('模块检查：')
    for line in ok:
        print('  ✅', line)
    if problems:
        print('\n❌ 问题：')
        for p in problems:
            print('  -', p)
        return 1
    print('\n✅ 全部通过（页数/标题/措辞/公式/插图）')
    return 0


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