# -*- coding: utf-8 -*-
"""《软件测试方法和技术（第4版）》HTML 课件生成器（仿《第八章生成式人工智能》模板布局）。
用法: python3 _build.py
结构: index.html（课程首页·17 次大课卡片）
      lectureN/N.M.html（第 N 次课第 M 页）+ lectureN/index.html（本课目录）
说明: 第 1 次课内容来自 _content1/_content2（48 页已完成）；
      第 2–16 次课当前为占位页（仅 index.html，slides 待制作）。
"""
import os, html as _h

ROOT = os.path.dirname(os.path.abspath(__file__))
HOME_TITLE = '软件测试课程设计'
HOME_SUB = '专业选修 · 课程编码 154442008'
HOME_PILL = '总学时 32 · 2 学分 ｜ 第 1–17 周（含实验）'
TEACHER_LINE = '授课教师：周宇文 ｜ 联系电话/微信：13580390715'

ROMAN = ['Ⅰ','Ⅱ','Ⅲ','Ⅳ','Ⅴ','Ⅵ','Ⅶ','Ⅷ','Ⅸ','Ⅹ','Ⅺ','Ⅻ','ⅩⅢ','ⅩⅣ','ⅩⅤ','ⅩⅥ','ⅩⅦ']

def esc(s):
    return _h.escape(s, quote=False)

LECTURES = [
 dict(no=1, title='第 1 章 引论——为什么必须做软件测试？', week='第1周',
      desc='课程导学＋1.1 必要性（真实缺陷事故）→ 1.2 为什么要测试 → 1.3 什么是软件测试（学科形成·正反思维·定义·新视角）→ 1.4 测试与SQA → 1.5 测试与开发 → 1.6 TDD 思想。', status='done'),
 dict(no=2, title='第 2 周', week='第2周', desc='', status='todo'),
 dict(no=3, title='第 3 周', week='第3周', desc='', status='todo'),
 dict(no=4, title='第 4 周', week='第4周', desc='', status='todo'),
 dict(no=5, title='第 5 周', week='第5周', desc='', status='todo'),
 dict(no=6, title='第 6 周', week='第6周', desc='', status='todo'),
 dict(no=7, title='第 7 周', week='第7周', desc='', status='todo'),
 dict(no=8, title='第 8 周', week='第8周', desc='', status='todo'),
 dict(no=9, title='第 9 周', week='第9周', desc='', status='todo'),
 dict(no=10, title='第 10 周', week='第10周', desc='', status='todo'),
 dict(no=11, title='第 11 周', week='第11周', desc='', status='todo'),
 dict(no=12, title='第 12 周', week='第12周', desc='', status='todo'),
 dict(no=13, title='第 13 周', week='第13周', desc='', status='todo'),
 dict(no=14, title='第 14 周', week='第14周', desc='', status='todo'),
 dict(no=15, title='第 15 周', week='第15周', desc='', status='todo'),
 dict(no=16, title='第 16 周', week='第16周', desc='', status='todo'),
 dict(no=17, title='第 17 周', week='第17周', desc='', status='todo'),
]

def slide_page(no, i, total, title, body, pt_prev, pt_next, href_prev, href_next, label):
    prev_block = ('<span class="nav-btn nav-disabled">◀</span>' if not href_prev
                  else '<a class="nav-btn" href="%s" title="上一页">◀</a>' % href_prev)
    next_block = ('<span class="nav-btn nav-disabled">▶</span>' if not href_next
                  else '<a class="nav-btn" href="%s" title="下一页">▶</a>' % href_next)
    quiz_extra = '<script src="../quiz.js"></script>' if ('class="quiz' in body) or ('quiz-opt' in body) or ('data-action=' in body) else ''
    return f'''<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>Slide {no}.{i} — {esc(title)}</title>
<link rel="stylesheet" href="../styles.css">
</head>
<body class="slide-page">

<div class="logo-bar"><img src="../logo.png" alt="Logo"><span class="logo-label">{label}</span></div>

<div class="slide-breadcrumb">
  <a href="../index.html">主页</a> / <a href="index.html">第{no}次课</a> / <span>{no}.{i}</span>
</div>

<div class="single-slide-page">
  <div class="single-slide-wrapper">
    <div class="slide-card">
      <div class="slide-number">Slide {no}.{i}</div>
      <div class="slide-title">{title}</div>
      <div class="slide-content">
        {body}
      </div>
    </div>
  </div>
  <div class="single-nav-bar">
    {prev_block}
    <div><span class="nav-label prev-label">{esc(pt_prev)}</span></div>
    <span class="nav-info">{no}.{i} / {total}</span>
    <div><span class="nav-label next-label">{esc(pt_next)}</span></div>
    {next_block}
  </div>
  <div class="kbd-hint">键盘 <kbd>←</kbd> <kbd>→</kbd> 或鼠标滚轮翻页</div>
</div>

<script>
document.addEventListener('keydown',e=>{{
  if(e.key==='ArrowRight'&&'{href_next}')window.location.href='{href_next}';
  if(e.key==='ArrowLeft'&&'{href_prev}')window.location.href='{href_prev}';
}});
let _wl=false;
document.addEventListener('wheel',e=>{{
  e.preventDefault();
  if(_wl)return;_wl=true;
  if(e.deltaY>0&&'{href_next}')window.location.href='{href_next}';
  else if(e.deltaY<0&&'{href_prev}')window.location.href='{href_prev}';
  setTimeout(()=>_wl=false,500);
}},{{passive:false}});
</script>
{quiz_extra}
</body>
</html>'''

def build_lecture1():
    import sys
    sys.path.insert(0, ROOT)
    from _content1 import SLIDES as S1
    slides = S1
    total = len(slides)
    assert total == 40, total
    folder = os.path.join(ROOT, 'lecture1')
    os.makedirs(folder, exist_ok=True)
    for i, (pt, title, body) in enumerate(slides, start=1):
        prev, nxt = i - 1, i + 1
        pt_prev = slides[prev - 1][0] if prev >= 1 else ''
        pt_next = slides[nxt - 1][0] if nxt <= total else ''
        href_prev = f'1.{prev}.html' if prev >= 1 else ''
        href_next = f'1.{nxt}.html' if nxt <= total else ''
        with open(os.path.join(folder, f'1.{i}.html'), 'w', encoding='utf-8') as f:
            f.write(slide_page(1, i, total, title, body, pt_prev, pt_next, href_prev, href_next,
                               '软件测试课程设计 · 第 1 次课'))
    groups = [
        ('一、封面 · 课程导学 · 教材定位 · 破冰', 1, 5),
        ('二、1.1 软件测试的必要性：国际事故 ＋“看图猜事故”', 6, 14),
        ('三、国产“血狮”案例', 15, 17),
        ('四、案例总回顾 · 缺陷归档', 18, 19),
        ('五、1.2 / 1.3 为什么要测 · 什么是软件测试', 20, 31),
        ('六、SQA · 开发 · TDD · 团队协作 · 岗位要求', 32, 37),
        ('七、本章小结 · 思考练习 · 学习资源', 38, 40),
    ]
    items = []
    for name, s, e in groups:
        items.append(f'    <div class="toc-section">{esc(name)} <em>第 {s}-{e} 页</em></div>')
        for i in range(s, e + 1):
            pt, title, _ = slides[i - 1]
            items.append(f'    <a class="toc-item" href="1.{i}.html"><span class="toc-num">1.{i}</span><span class="toc-title">{esc(title)}</span><span class="toc-arrow">→</span></a>')
    with open(os.path.join(folder, 'index.html'), 'w', encoding='utf-8') as f:
        f.write(f'''<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>第1次课 — 目录</title>
<link rel="stylesheet" href="../styles.css">
<style>
.toc-section{{margin:24px 0 8px;padding:8px 14px;background:linear-gradient(135deg,#1a365d,#2b6cb0);color:#fff;border-radius:8px;font-size:1.05rem;font-weight:700;letter-spacing:.5px;}}
.toc-section:first-of-type{{margin-top:12px;}}
.toc-section em{{font-style:normal;font-weight:400;opacity:.85;font-size:.9rem;margin-left:6px;}}
</style>
</head>
<body>

<div class="logo-bar">
  <img src="../logo.png" alt="Logo">
  <span class="logo-label">软件测试课程设计 · 第 1 次课</span>
</div>

<div class="breadcrumb">
  <a href="../index.html">← 返回主页</a>
</div>

<div class="toc-page">
  <h2>🕒 第 1 次课（第 1 周）：第 1 章 引论——为什么必须做软件测试？</h2>
  <div class="toc-subtitle">{total} 张幻灯片 · 点击任意标题直接跳转（键盘 ← → 或滚轮翻页）</div>
  <div class="toc-subtitle">👩‍🏫 {TEACHER_LINE}</div>

  <div class="toc-progress">
    <span>0/{total}</span>
    <div class="progress-bar"><div class="progress-fill" style="width:0%"></div></div>
  </div>

  <div class="toc-list">

{chr(10).join(items)}

  </div>
  <p style="text-align:center;margin:22px 0 6px;">
    <a href="../resources.html" style="text-decoration:none;color:#2b6cb0;font-size:1.05rem;">📚 参考资料下载 →</a>
  </p>
</div>
</body>
</html>''')
    print('lecture1 built:', total, 'slides + toc')

def placeholder_page(no, week, title, desc, slides_target):
    return f'''<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>第{no}次课 — 未开放观看</title>
<link rel="stylesheet" href="../styles.css">
</head>
<body>

<div class="logo-bar">
  <img src="../logo.png" alt="Logo">
  <span class="logo-label">软件测试课程设计 · 第 {no} 次课</span>
</div>

<div class="home-container" style="text-align:center;">
  <div class="home-hero">
    <h1>未开放观看</h1>
    <div class="subtitle">第 {no} 次课（{esc(week)}）：{esc(title)}</div>
    <div style="margin-top:14px;color:#718096;">👩‍🏫 {TEACHER_LINE}</div>
  </div>
  <div style="margin-top:10px;">
    <a href="../index.html" style="display:inline-flex;align-items:center;gap:8px;border-radius:12px;padding:12px 34px;text-decoration:none;color:#fff;background:linear-gradient(135deg,#2b6cb0,#3182ce);font-size:1.05rem;">← 返回主页</a>
  </div>
</div>
</body>
</html>'''

def build_placeholders():
    targets = {3:24,4:24,5:24,6:24,7:24,8:24,9:22,10:24,11:24,12:30,13:30,14:30,15:30,16:32}
    for L in LECTURES:
        if L['no'] == 1 or L['status'] != 'todo':
            continue
        folder = os.path.join(ROOT, f'lecture{L["no"]}')
        os.makedirs(folder, exist_ok=True)
        with open(os.path.join(folder, 'index.html'), 'w', encoding='utf-8') as f:
            f.write(placeholder_page(L['no'], L['week'], L['title'], L['desc'],
                                     targets.get(L['no'], 26)))
    print('placeholders built:', 15)

def build_home():
    cards = []
    for L in LECTURES:
        n = L['no']
        if n == 1:
            link, status_line = 'lecture1/index.html', '📋 查看全部 40 页 →'
        else:
            link, status_line = f'lecture{n}/index.html', '🔒 未开放观看 →'
        desc_html = f'<div class="card-desc">{esc(L["desc"])}</div>' if L.get('desc') else ''
        cards.append(f'''    <a class="lecture-card" href="{link}">
      <div class="card-banner">{ROMAN[n - 1]}</div>
      <div class="card-body">
        <h3>{esc(L['title'])}</h3>
        <div class="card-time">{esc(L['week'])} · 2 课时</div>
        {desc_html}
        <span class="lecture-overview-link">{status_line}</span>
        <div class="card-arrow">→</div>
      </div>
    </a>''')
    with open(os.path.join(ROOT, 'index.html'), 'w', encoding='utf-8') as f:
        f.write(f'''<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>{HOME_TITLE} — 17 次大课</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>

<div class="logo-bar">
  <img src="logo.png" alt="Logo">
  <span class="logo-label">软件测试课程设计 · 17 次大课</span>
</div>

<div class="home-container">
  <div class="home-hero">
    <h1>{HOME_TITLE}</h1>
    <div class="subtitle">{HOME_SUB}</div>
    <div class="subtitle">👩‍🏫 {TEACHER_LINE}</div>
    <span class="audience">{HOME_PILL}</span>
  </div>

  <div class="lecture-cards">
{chr(10).join(cards)}
  </div>

  <p style="text-align:center;margin:30px 0 10px;">
    <a href="resources.html" style="display:inline-block;padding:12px 26px;border-radius:12px;text-decoration:none;color:#fff;background:linear-gradient(135deg,#2b6cb0,#3182ce);font-size:1.05rem;">📚 参考资料下载（标准规范 / 报告 / 知识地图）</a>
  </p>
</div>
</body>
</html>''')
    print('home built')

if __name__ == '__main__':
    build_lecture1()
    build_placeholders()
    build_home()
