# -*- coding: utf-8 -*-
"""批量流水线：把《软件测试方法和技术》第 5–14 章原 PPT 做成可以上线的学生版网页。

每章四步：
  ① 换图（同济校园照／校名石碑 → 广金）→ 课件PPT-GDUF版/ChN-<章名>-GDUF版.pptx
  ② soffice 转 PDF → _convN/
  ③ pdftoppm 渲染逐页 PNG（统一补零成 3 位）→ _convN/assets/page/slide-001.png …
  ④ _extract.py 抽文字 ＋ _build_student.py 生成学生版 → _deploy/stmt-lectureN

用法：python _pipeline_all.py [章号...]（不带参数=第 5–14 章全跑）
"""
import glob
import hashlib
import json
import os
import re
import shutil
import subprocess
import sys
import zipfile

BASE = os.path.dirname(os.path.abspath(__file__))
SRC = os.path.join(BASE, '课件PPT-加校徽')
DST = os.path.join(BASE, '课件PPT-GDUF版')
PY = sys.executable
KNOWN = {'5b14042c7a': ('校园', '1780x1000@0.53@0.58@0.27'),
         '858ef6afb2': ('石碑', '2130x1000@0.56@0.70@0.25')}


def media_hashes(pptx):
    z = zipfile.ZipFile(pptx)
    return {n.split('/')[-1]: hashlib.sha1(z.read(n)).hexdigest()[:10]
            for n in z.namelist() if n.startswith('ppt/media/')}


def find_src(n):
    hits = [p for p in glob.glob(os.path.join(SRC, 'Ch%d*.pptx' % n))
            if re.match(r'Ch%d(?!\d)' % n, os.path.basename(p))]
    return hits[0] if hits else None


def chapter_title(path, n):
    name = os.path.basename(path)
    name = re.sub(r'^Ch\d+[\s\-－_]*', '', name)
    name = re.sub(r'[-_－]?(STMT-2022|2022|STMT-202)\b', '', name)
    name = re.sub(r'\.pptx$', '', name)
    name = re.sub(r'^STMT-2022', '', name).strip(' -－_')
    return '第 %d 章 %s' % (n, name or '未命名'), (name or '未命名')


def run(cmd, **kw):
    r = subprocess.run(cmd, shell=isinstance(cmd, str), capture_output=True, text=True,
                       env={**os.environ, 'TMPDIR': os.path.join(BASE, 'tmp_home')}, **kw)
    return r


def main():
    nums = [int(x) for x in sys.argv[1:]] or list(range(5, 15))
    os.makedirs(os.path.join(BASE, 'tmp_home'), exist_ok=True)
    report = []
    for n in nums:
        src = find_src(n)
        if not src:
            print('✗ 第 %d 章：找不到源 PPT' % n); report.append((n, '找不到源 PPT', 0)); continue
        title, short = chapter_title(src, n)
        gduf = os.path.join(DST, 'Ch%d-%s-GDUF版.pptx' % (n, short))
        # ① 换图
        specs, hits = [], []
        for name, h in media_hashes(src).items():
            if h in KNOWN:
                kind, spec = KNOWN[h]
                specs.append('%s=%s' % (name, spec)); hits.append('%s(%s)' % (name, kind))
        if not os.path.exists(gduf):
            if specs:
                run([PY, os.path.join(BASE, '_brand_work', '_gduf_apply.py'), src, gduf] + specs)
            else:
                shutil.copy2(src, gduf)
        # ② PDF
        conv = os.path.join(BASE, '_conv%d' % n)
        os.makedirs(os.path.join(conv, 'assets', 'page'), exist_ok=True)
        pdf = os.path.join(conv, os.path.basename(gduf).replace('.pptx', '.pdf'))
        if not os.path.exists(pdf):
            run('soffice --headless --norestore -env:UserInstallation=file://%s/tmp_home/lo%d '
                '--convert-to pdf --outdir "%s" "%s"'
                % (BASE, n, conv, gduf))
        if not os.path.exists(pdf):
            print('✗ 第 %d 章：PDF 转换失败' % n); report.append((n, 'PDF 转换失败', 0)); continue
        # ③ 渲染
        pngs = glob.glob(os.path.join(conv, 'assets', 'page', 'slide-*.png'))
        if len(pngs) < 5:
            run(['pdftoppm', '-r', '150', '-png', pdf,
                 os.path.join(conv, 'assets', 'page', 'slide')])
            for f in glob.glob(os.path.join(conv, 'assets', 'page', 'slide-*.png')):
                b = os.path.basename(f)
                m = re.match(r'slide-(\d+)\.png$', b)
                if m and len(m.group(1)) != 3:
                    os.rename(f, os.path.join(conv, 'assets', 'page', 'slide-%03d.png' % int(m.group(1))))
        pages = len(glob.glob(os.path.join(conv, 'assets', 'page', 'slide-*.png')))
        # ④ 抽取 + 学生版
        data = os.path.join(conv, '_data', 'slides.json')
        if not os.path.exists(data):
            run([PY, os.path.join(BASE, '_conv_work', '_extract.py'), gduf, conv])
        ans = os.path.join(conv, '_answers.json')
        out = os.path.join(BASE, '_deploy', 'stmt-lecture%d' % n)
        r = run([PY, os.path.join(BASE, '_conv_work', '_build_student.py'), conv, out,
                 '软件测试课程设计', title] + ([ans] if os.path.exists(ans) else []))
        ok = os.path.exists(os.path.join(out, 'index.html'))
        print('%-2d %-26s 页 %3d ｜ 换图 %d ｜ 学生版 %s' % (n, title, pages, len(hits), '✓' if ok else '✗ '+r.stderr[-200:]))
        report.append((n, title, pages))
    print('\n合计 %d 章 / %d 页' % (len(report), sum(r[2] for r in report if isinstance(r[2], int))))
    json.dump(report, open(os.path.join(BASE, '_pipeline_report.json'), 'w'), ensure_ascii=False, indent=1)


if __name__ == '__main__':
    main()
