# -*- coding: utf-8 -*-
"""第 5、6 次课课件校验（内容模块 + 生成的 HTML）
用法：python3 _check56.py
检查：
  1) 六个内容模块能否导入、页数是否为 14/16/14（讲A）与 15/15/15（讲B）
  2) 每页三元组结构是否为 (锚点, 标题, HTML) 且标题/正文非空
  3) 正文引用的插图（../assets/第4章/xxx.png）是否真实存在
  4) 生成后的 HTML 文件数、styles.css 版本号、页脚页码总数是否一致
  5) 页内若出现右双引号未配对等常见 Python 拼接错误（在导入阶段即会暴露）
"""
import os, re, sys, glob

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

from _build import CSS_VER
import _content5a, _content5b, _content5c, _content6a, _content6b, _content6c

MODS = [('_content5a', _content5a.SLIDES_5A, 14), ('_content5b', _content5b.SLIDES_5B, 16),
        ('_content5c', _content5c.SLIDES_5C, 14), ('_content6a', _content6a.SLIDES_6A, 15),
        ('_content6b', _content6b.SLIDES_6B, 15), ('_content6c', _content6c.SLIDES_6C, 15)]
bad = []
total_pages = 0
print(f'{"模块":<14}{"页数":>5}{"应":>5}  插图  问题')
for name, slides, want in MODS:
    total_pages += len(slides)
    imgs, probs = [], []
    for idx, item in enumerate(slides, 1):
        if not (isinstance(item, (tuple, list)) and len(item) == 3):
            probs.append(f'第{idx}页结构异常'); continue
        pt, title, body = item
        if not str(pt).strip() or not str(title).strip():
            probs.append(f'第{idx}页锚点/标题为空')
        if not str(body).strip():
            probs.append(f'第{idx}页正文为空')
        for src in re.findall(r"<img[^>]+src=[\"']([^\"']+)[\"']", str(body)):
            imgs.append(src)
            # 页面文件位于 lectureN/ 下，故 ../assets/x 需相对 lectureN 解析
            no = 5 if name.startswith('_content5') else 6
            p = os.path.normpath(os.path.join(ROOT, f'lecture{no}', src))
            if not os.path.isfile(p):
                probs.append(f'第{idx}页缺图 {src}')
    if len(slides) != want:
        probs.append(f'页数应为 {want}，实际 {len(slides)}')
    print(f'{name:<14}{len(slides):>5}{want:>5}{len(imgs):>6}  ' + ('⚠️ ' + '；'.join(probs[:4]) if probs else '✅'))
    bad += probs

print(f'\n内容模块合计 {total_pages} 页（讲A 44 + 讲B 45 = 89）')

# 生成的 HTML
for no, want in ((5, 44), (6, 45)):
    files = sorted(glob.glob(f'lecture{no}/{no}.*.html'))
    toc = os.path.isfile(f'lecture{no}/index.html')
    vers = set()
    for f in files:
        m = re.search(r'styles\.css\?v=([0-9a-z]+)', open(f, encoding='utf-8').read())
        vers.add(m.group(1) if m else '无')
    ok = len(files) == want and toc and vers == {CSS_VER}
    print(f'lecture{no}: HTML {len(files)}/{want} 页 ｜ 目录页 {"有" if toc else "缺"} ｜ '
          f'CSS 版本 {sorted(vers)}（当前 {CSS_VER}）  ' + ('✅' if ok else '⚠️'))
    if not ok:
        bad.append(f'lecture{no} 生成异常')

print()
if bad:
    print('⚠️ 发现问题：')
    for b in bad:
        print('  -', b)
    sys.exit(1)
print('✅ 第 5、6 次课课件校验全部通过')
