# -*- coding: utf-8 -*-
"""课件「教师向内容」排查：找不适合学生看到的标注/提醒/素材出处等。
用法：python3 _scan_teacher_meta.py [课件根目录]
输出：按模式分组，给出命中文件、次数与示例片段。
"""
import os, re, sys, glob, html
from collections import defaultdict

ROOT = sys.argv[1] if len(sys.argv) > 1 else os.path.dirname(os.path.abspath(__file__))
FILES = sorted(glob.glob(os.path.join(ROOT, 'lecture*', '*.html'))) + \
        sorted(glob.glob(os.path.join(ROOT, 'index.html')))

# 模式 → 说明（按"越靠前越像教师向"排序）
PATTERNS = [
    ('课上可跳过', r'课上可跳过|课上跳过|课堂可跳过'),
    ('教师/老师向', r'教师|老师|授课建议|备课|教学建议|讲师'),
    ('讲稿/教案引用', r'讲稿|教案|本讲稿|授课稿'),
    ('素材出处标注', r'教材\s*[Pp]\s*\d+|教材第\s*\d+\s*页|PPT\s*第?\s*\d+\s*页|课件提纲|PPT\s*\d+\s*[–\-~]\s*\d+\s*页'),
    ('课堂教学编排提示', r'课堂讨论用|供小组|小组复盘|课堂示例|课堂练习（口头）|建议用时|建议讲|本页建议|互动点|板书|口播'),
    ('命题/答案向', r'命题|出题|答案要点|参考答案|题库|评分标准|评分观察点|阅卷'),
    ('自拟/示例口径', r'自拟|示例数据|课堂演示用|演示用数据|非教材'),
    ('本次课覆盖/进度', r'本讲覆盖|本次课覆盖|留给讲B|讲B\s*再|讲A'),
    ('页数/板块统计', r'\d+\s*张幻灯片|板块|★课后拓展'),
]

def strip_html(s):
    s = re.sub(r'<script.*?</script>', ' ', s, flags=re.S)
    s = re.sub(r'<style.*?</style>', ' ', s, flags=re.S)
    s = re.sub(r'<[^>]+>', ' ', s)
    return html.unescape(re.sub(r'\s+', ' ', s))

hits = defaultdict(list)
for f in FILES:
    raw = open(f, encoding='utf-8').read()
    txt = strip_html(raw)
    rel = os.path.relpath(f, ROOT)
    for name, pat in PATTERNS:
        for m in re.finditer(pat, txt):
            a = max(0, m.start() - 45); b = min(len(txt), m.end() + 45)
            hits[name].append((rel, txt[a:b].strip()))

print(f'扫描文件 {len(FILES)} 个（课件页 + 主页）\n' + '=' * 96)
total = 0
for name, _ in PATTERNS:
    rows = hits.get(name, [])
    total += len(rows)
    files = sorted({r for r, _ in rows})
    print(f'\n【{name}】命中 {len(rows)} 处，涉及 {len(files)} 个文件')
    if not rows:
        continue
    for r, s in rows[:4]:
        print(f'   - {r}: …{s}…')
    if len(rows) > 4:
        print(f'   …（另有 {len(rows)-4} 处）')
    if files:
        print(f'   文件：{", ".join(files[:8])}' + ('…' if len(files) > 8 else ''))
print(f'\n{"=" * 96}\n合计命中 {total} 处')
