#!/usr/bin/env python3
"""Build standalone HTML slide decks from the role manuals (one deck per manual)."""
import os, re, glob, html, json
from PIL import Image
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
MD = os.path.join(ROOT, 'markdown')
OUT = os.path.join(ROOT, 'slides')

CASES = {
 'M01': '新签约的运营单位明天要开班，但账号、实训舱、时段、课程都没配好——平台管理员如何用半天完成开通？',
 'M02': '周一早上，3 个舱、5 名学员、1 场考试同时进行，运营单位管理员先看什么、后做什么？',
 'M03': '学员小王报名后一周没来实训，运营管理员如何从数据里发现并跟进？',
 'M04': '培训运营接到一门新课，要在两周内完成建课、配物料、绑舱、发布，最短路径是什么？',
 'M05': '开课前 30 分钟，舱门打不开、网关离线、告警不断——运维如何判断先修哪一段？',
 'M06': '一条停课公告，学员说没看到；一条操作指引，学员说看不懂——内容运营怎么排查？',
 'M07': '同一小组 3 名学员连续 2 次实训未通过，助教如何判断是课程、设备还是学员问题？',
 'M08': '学员已签到但门锁无响应，教师如何用小程序在 2 分钟内完成应急开门并留痕？',
 'M09': '第一次到舱的学员，从入组到开始实训要过几道关？最容易卡在哪一步？',
 'M10': '学员投诉“约了 3 次都没约上”，情绪激动——客服如何分级、转派、回复？',
 'M11': '一场考试报名 40 人、含主观题、还要监考——四个考试角色如何交接不漏项？',
}

DECKS = {
 'M01': ('M01-platform-admin', '#1D4ED8', '#0EA5E9'),
 'M02': ('M02-tenant-admin', '#0F766E', '#14B8A6'),
 'M03': ('M03-operation-admin', '#7C3AED', '#A78BFA'),
 'M04': ('M04-training-admin', '#B45309', '#F59E0B'),
 'M05': ('M05-device-ops', '#B91C1C', '#F97316'),
 'M06': ('M06-content-admin', '#BE185D', '#EC4899'),
 'M07': ('M07-tutor', '#4338CA', '#818CF8'),
 'M08': ('M08-teacher', '#047857', '#34D399'),
 'M09': ('M09-student', '#0369A1', '#38BDF8'),
 'M10': ('M10-customer-service', '#9333EA', '#C084FC'),
 'M11': ('M11-exam', '#9F1239', '#FB7185'),
}

def esc(t): return html.escape(t, quote=False)

def inline(t):
    t = esc(t)
    t = re.sub(r'\*\*([^*]+)\*\*', r'<strong>\1</strong>', t)
    t = re.sub(r'`([^`]+)`', r'<code>\1</code>', t)
    t = re.sub(r'\[([^\]]+)\]\([^)]+\)', r'<span class="link">\1</span>', t)
    t = re.sub(r'!\[[^\]]*\]\([^)]+\)', '', t)
    return t

def clean(t):
    t = re.sub(r'!\[[^\]]*\]\([^)]+\)', '', t)
    t = re.sub(r'\[([^\]]+)\]\([^)]+\)', r'\1', t)
    t = t.replace('**','').replace('`','')
    t = re.sub(r'^\s*[-*]\s*', '', t)
    t = re.sub(r'^\[.?\]\s*', '', t)
    return t.strip()

def asset_path(src):
    for p in [os.path.normpath(os.path.join(ROOT,src)), os.path.normpath(os.path.join(ROOT,'markdown',src)), os.path.normpath(os.path.join(ROOT,src.lstrip('../')))]:
        if os.path.exists(p): return p
    return os.path.normpath(os.path.join(ROOT,src))

def is_tall(src):
    p=asset_path(src)
    try:
        w,h=Image.open(p).size
        return h/w>2.0
    except Exception:
        return False

def is_wide(src):
    p=asset_path(src)
    try:
        w,h=Image.open(p).size
        return w/h>2.5
    except Exception:
        return False

def flow_steps(src):
    p=os.path.splitext(asset_path(src))[0]+'.puml'
    if not os.path.exists(p): return []
    steps=[]
    for line in open(p,encoding='utf-8'):
        line=line.strip()
        m=re.match(r'^:([^;]+);',line)
        if m:
            t=re.sub(r'<<[^>]*>>','',m.group(1)).strip()
            t=re.sub(r'\[.*?\]','',t).strip()
            if t: steps.append(t)
        m=re.match(r'^state "([^"]+)"',line)
        if m and '[' not in m.group(1): steps.append(m.group(1).strip())
    return steps

def parse(path):
    lines = open(path, encoding='utf-8').read().splitlines()
    title = '培训教材'; meta = {}
    for line in lines:
        if line.startswith('# '): title = line[2:].strip(); break
    KNOWN={'适用角色','教材编号','版本','更新日期','建议课时','配套课件'}
    for line in lines:
        if line.startswith('## '): break
        for k,v in re.findall(r'\*\*([^*]+)\*\*[：:]\s*([^*]*?)(?=\s*\*\*|$)', line):
            k=k.strip()
            if k in KNOWN: meta[k]=clean(v.strip())
    blocks = []; i = 0
    while i < len(lines):
        line = lines[i].rstrip()
        if not line.strip(): i += 1; continue
        if line.strip() == '---': i += 1; continue
        if line.startswith('## '):
            blocks.append({'t':'h2','text':line[3:].strip()}); i += 1; continue
        if line.startswith('### '):
            blocks.append({'t':'h3','text':line[4:].strip()}); i += 1; continue
        if line.startswith('#### '):
            blocks.append({'t':'h4','text':line[5:].strip()}); i += 1; continue
        img = re.match(r'!\[([^\]]*)\]\(([^)]+)\)', line.strip())
        if img:
            cap = ''; j = i + 1
            while j < len(lines) and not lines[j].strip():
                j += 1
            if j < len(lines) and lines[j].strip().startswith('*图'):
                cap = lines[j].strip().strip('*'); i = j + 1
            else:
                i += 1
            blocks.append({'t':'img','src':img.group(2),'cap':cap}); continue
        if line.strip().startswith('|'):
            rows = []
            while i < len(lines) and lines[i].strip().startswith('|'):
                raw = lines[i].strip().strip('|')
                if not re.match(r'^[\s:\-|]+$', raw):
                    rows.append([clean(c).strip() for c in raw.split('|')])
                i += 1
            blocks.append({'t':'table','rows':rows}); continue
        if line.startswith('> '):
            blocks.append({'t':'quote','text':line[2:].strip()}); i += 1; continue
        m = re.match(r'^\s*[-*]\s+(.*)$', line)
        if m:
            items = [m.group(1)]
            i += 1
            while i < len(lines) and re.match(r'^\s*[-*]\s+', lines[i]):
                items.append(re.sub(r'^\s*[-*]\s+','',lines[i])); i += 1
            blocks.append({'t':'ul','items':items}); continue
        m = re.match(r'^\s*\d+[.、]\s+(.*)$', line)
        if m:
            items = [m.group(1)]
            i += 1
            while i < len(lines) and re.match(r'^\s*\d+[.、]\s+', lines[i]):
                items.append(re.sub(r'^\s*\d+[.、]\s+','',lines[i])); i += 1
            blocks.append({'t':'ol','items':items}); continue
        blocks.append({'t':'p','text':line.strip()}); i += 1
    return title, meta, blocks

def chunks(items, n): return [items[i:i+n] for i in range(0,len(items),n)]

def build_slides(title, meta, blocks, case=''):
    slides = []
    # chapters
    chapters=[]; cur=None
    for b in blocks:
        if b['t']=='h2':
            cur={'title':b['text'],'blocks':[]}; chapters.append(cur)
        elif cur is not None:
            cur['blocks'].append(b)
    # objectives from 学习目标
    objectives=[]
    for c in chapters:
        if '学习目标' in c['title']:
            for b in c['blocks']:
                if b['t'] in ('ul','ol'): objectives += [clean(x) for x in b['items']]
    objectives = objectives[:7]
    role_line = meta.get('适用角色','')
    # cover
    slides.append({'type':'cover','title':title,'subtitle':'运营单位岗位培训教材','meta':meta,'chips':role_line})
    # objectives
    slides.append({'type':'objectives','title':'学习目标','items':objectives,'kicker':'完成本课后，你应当能够'})
    if case:
        slides.append({'type':'case','title':'从一个真实场景开始','text':case})
    # agenda
    agenda=[c['title'] for c in chapters if '学习目标' not in c['title'] and not c['title'].startswith('附录')]
    slides.append({'type':'agenda','title':'课程地图','items':agenda})
    # chapters
    for ci,c in enumerate(chapters):
        t=c['title']
        if '学习目标' in t: continue
        if t.startswith('附录'):
            # appendix as compact reference slide
            points=[]
            for b in c['blocks']:
                if b['t']=='table':
                    for row in b['rows'][1:6]: points.append(' · '.join(row))
                elif b['t'] in ('ul','ol'):
                    points += [clean(x) for x in b['items']][:6]
            if points: slides.append({'type':'content','kicker':'附录','title':t,'bullets':points[:7]})
            continue
        # divider
        def lead_ok(b):
            if b['t'] != 'p': return False
            x = clean(b['text']).strip()
            return len(x) > 18 and '。' in x and not x.startswith('图 ') and not x.startswith('路径') and not x.startswith('步骤') and not x.endswith('*') and not x.startswith('*')
        lead = next((clean(b['text']).strip('*') for b in c['blocks'] if lead_ok(b)), '')
        if not lead:
            lead = f'本章聚焦“{t}”，先讲原理，再演示操作。'

        lead=lead[:90]
        if lead.endswith('原则：') or lead.endswith('原则:'):
            lead = f'本章聚焦“{t}”，说明配置边界与验证方式。'
        lead = lead.rstrip('：:') + '。本章逐项拆解。' if (lead.endswith('：') or lead.endswith(':')) else lead
        slides.append({'type':'section','num':f'{ci:02d}','title':t,'lead':lead})
        # group by h3
        groups=[]; g={'title':None,'blocks':[]}
        for b in c['blocks']:
            if b['t']=='h3':
                if g['blocks'] or g['title']: groups.append(g)
                g={'title':b['text'],'blocks':[]}
            else: g['blocks'].append(b)
        if g['blocks'] or g['title']: groups.append(g)
        if len(groups) > 1:
            groups = [g for g in groups if not (g['title'] is None and not any(b['t'] in ('img','table') for b in g['blocks']) and not any(b['t'] in ('ul','ol') for b in g['blocks']))]
        if not groups: groups=[{'title':None,'blocks':c['blocks']}]
        for g in groups:
            bullets=[]; imgs=[]; tables=[]; quotes=[]
            for b in g['blocks']:
                if b['t'] in ('ul','ol'):
                    bullets += [clean(x) for x in b['items']]
                elif b['t']=='p':
                    x=clean(b['text'])
                    if len(x)>12: bullets.append(x)
                elif b['t']=='img': imgs.append(b)
                elif b['t']=='table': tables.append(b)
                elif b['t']=='quote': quotes.append(clean(b['text']))
            # drop captions / very long
            bullets=[x for x in bullets if not x.startswith('图 ')][:8]
            if not bullets and not imgs and not tables and not quotes: continue
            title=g['title'] or ('流程总览' if imgs else (t + ' · 关键判断' if any(b['t'] in ('ul','ol') for b in g['blocks']) else t))
            # text+image slide(s)
            if imgs:
                for k,im in enumerate(imgs[:2]):
                    if 'diagrams' in im['src'] and is_tall(im['src']):
                        steps=flow_steps(im['src'])
                        if len(steps)>=3:
                            slides.append({'type':'flow','kicker':t,'title':title,'steps':steps[:10],'cap':im['cap'],'bullets':bullets[:3]})
                            continue
                    src=im['src']
                    cand=os.path.splitext(asset_path(src))[0]+'-slide.png'
                    if os.path.exists(cand):
                        src='../assets/diagrams/'+os.path.relpath(cand,os.path.join(ROOT,'assets','diagrams')).replace(os.sep,'/')
                    if 'diagrams' in src and is_wide(asset_path(src)):
                        slides.append({'type':'wideimg','kicker':t,'title':title,'bullets':bullets[:3],'img':src,'cap':im['cap']})
                    else:
                        slides.append({'type':'visual','kicker':t,'title':title,'bullets':bullets[:4],'img':src,'cap':im['cap'],'flip':k%2==1})
            else:
                if bullets or quotes:
                    slides.append({'type':'content','kicker':t,'title':title,'bullets':bullets[:6],'quote':quotes[0] if quotes else ''})
            if tables:
                for tb in tables[:1]:
                    rows=tb['rows'][:7]
                    if rows: slides.append({'type':'table','kicker':t,'title':title+' · 要点表','rows':rows})
    # quiz
    quiz=[]
    for c in chapters:
        if '考核' in c['title'] or '测验' in c['title']:
            in_quiz = False
            for b in c['blocks']:
                if b['t']=='h3':
                    in_quiz = ('情景测验' in b['text']) or ('测验' in b['text'] and '演练' not in b['text'])
                    continue
                if in_quiz and b['t']=='ol':
                    quiz += [clean(x) for x in b['items']]
    answers=[]
    for c in chapters:
        if '考核' in c['title']:
            in_ans=False
            for b in c['blocks']:
                if b['t']=='h3' and '答案' in b['text']: in_ans=True; continue
                if b['t']=='h3': in_ans=False
                if in_ans and b['t']=='ol': answers += [clean(x) for x in b['items']]
    quiz=quiz[:10]; answers=answers[:10]
    if quiz: slides.append({'type':'quiz','title':'课堂测验','items':quiz,'answers':answers})
    # consolidate content-only slides when deck is long
    if len(slides)>42:
        merged=[]; i=0
        while i<len(slides):
            cur=slides[i]
            if cur['type']=='content' and not cur.get('quote'):
                group=[cur]; j=i+1
                while j<len(slides) and slides[j]['type']=='content' and slides[j].get('kicker')==cur.get('kicker') and len(sum([g.get('bullets',[]) for g in group],[]))<4:
                    group.append(slides[j]); j+=1
                if len(group)>1:
                    bullets=[]
                    for g in group:
                        for b in g.get('bullets',[]): bullets.append(b)
                    merged.append({'type':'content','kicker':cur.get('kicker'),'title':cur.get('title'),'bullets':bullets[:6]})
                    i=j; continue
            merged.append(cur); i+=1
        slides=merged
    # summary
    redlines=[clean(x) for b in blocks if b['t']=='ul' for x in b['items'] if ('红线' in x or '必须' in x)][:4]
    slides.append({'type':'summary','title':'本课小结','redlines':redlines or ['先确认权限边界，再开始操作','所有异常都要闭环并留记录','不确定时先停下，向上级或平台求助'],'homework':'回岗后 7 天内：完成一次本岗位完整业务闭环，并提交 1 条改进建议。'})
    slides.append({'type':'end','title':'谢谢','subtitle':'把教材带回岗位，把流程变成习惯'})
    return slides

def render(slides, deck_title, accent, accent2):
    out=[]
    for idx,s in enumerate(slides,1):
        t=s['type']; notes=''
        kicker_html='' if s.get('kicker')==s.get('title') else f'<div class="kicker">{esc(s.get("kicker",""))}</div>'
        if t=='cover':
            body=f'''<div class="cover-bg"></div>
<div class="cover-content">
  <div class="brand">AI 实训舱 · 运营单位培训</div>
  <h1>{esc(s['title'].replace('培训教材',''))}</h1>
  <p class="sub">{esc(s['subtitle'])}</p>
  <div class="chips">{''.join(f'<span>{esc(x)}</span>' for x in re.split(r'[、,，/]', s['chips']) if x.strip())}</div>
  <div class="cover-meta">{''.join(f'<div><b>{esc(k)}</b><span>{esc(v)}</span></div>' for k,v in list(s['meta'].items())[:6])}</div>
</div>'''
            notes='开场：用一个学员从报名到结训的故事，引出本岗位在链路中的位置。'
        elif t=='objectives':
            items=''.join(f'<div class="obj"><span>{i:02d}</span><p>{inline(x)}</p></div>' for i,x in enumerate(s['items'],1))
            body=f'<div class="slide-head"><div class="kicker">{esc(s["kicker"])}</div><h2>{esc(s["title"])}</h2></div><div class="obj-grid">{items}</div>'
            notes='逐条读目标，让学员对照自己的岗位勾选“今天最想解决的 2 条”。'
        elif t=='case':
            body=f'''<div class="case-wrap"><div class="kicker">情境导入</div><h2>{esc(s['title'])}</h2><blockquote>{esc(s['text'])}</blockquote><div class="case-ask"><b>讨论 3 分钟</b><span>如果是你，第一步做什么？最怕漏掉什么？</span></div></div>'''
            notes='先不讲解，点名 2–3 位学员回答；把答案写在白板上，课程结束时回看。'
        elif t=='agenda':
            items=''.join(f'<div class="agenda-item"><span>{i:02d}</span><p>{esc(x)}</p></div>' for i,x in enumerate(s['items'],1))
            body=f'<div class="slide-head"><div class="kicker">课程结构</div><h2>{esc(s["title"])}</h2></div><div class="agenda-grid">{items}</div>'
            notes='说明课程节奏：每章先讲原理，再演示，再让学员操作。'
        elif t=='section':
            body=f'''<div class="section-wrap"><div class="section-num">{esc(s['num'])}</div><div><div class="kicker">章节</div><h2>{esc(s['title'])}</h2><p class="lead">{esc(s['lead'])}</p></div></div>'''
            notes='过渡页：' + (s.get('lead') or '用一句话说明本章解决什么问题。')
        elif t in ('content','visual'):
            bullets=''.join(f'<li>{inline(x)}</li>' for x in s.get('bullets',[]))
            quote=f'<div class="callout">{inline(s["quote"])}</div>' if s.get('quote') else ''
            if t=='visual':
                img=f'<figure class="shot"><img src="{esc(s["img"])}" alt="{esc(s["cap"])}"><figcaption>{esc(s["cap"])}</figcaption></figure>'
                cls='screen' if 'screenshots' in s.get('img','') else ''
                if 'screenshots' in s.get('img','') and ('/M09/' in s.get('img','') or '/M08/' in s.get('img','')): cls='phone'
                body=f'''<div class="slide-head">{kicker_html}<h2>{esc(s['title'])}</h2></div>
<div class="two-col {cls} {'flip' if s.get('flip') else ''}"><div class="text"><ul>{bullets}</ul>{quote}</div>{img}</div>'''
            else:
                body=f'''<div class="slide-head">{kicker_html}<h2>{esc(s['title'])}</h2></div>
<div class="content-body"><ul class="big-list">{bullets}</ul>{quote}</div>'''
            notes='讲解要点：' + '；'.join(s.get('bullets',[])[:2]) + '。先讲“为什么”，再演示“怎么做”，最后提醒一个易错点。' if s.get('bullets') else '先讲“为什么”，再演示“怎么做”，最后提醒一个易错点。'
        elif t=='wideimg':
            chips=''.join(f'<span>{inline(x)}</span>' for x in s.get('bullets',[]))
            body=f'''<div class="slide-head">{kicker_html}<h2>{esc(s['title'])}</h2></div>
<div class="wide-chips">{chips}</div><figure class="shot wide-shot"><img src="{esc(s['img'])}" alt="{esc(s.get('cap',''))}"><figcaption>{esc(s['cap'])}</figcaption></figure>'''
            notes='先让学员看图找自己的位置，再按图讲一遍端到端流程。'
        elif t=='flow':
            cards=''.join(f'<div class="flow-card"><b>{i:02d}</b><span>{inline(x)}</span></div>' for i,x in enumerate(s['steps'],1))
            body=f'''<div class="slide-head">{kicker_html}<h2>{esc(s['title'])}</h2></div>
<div class="flow-grid">{cards}</div><div class="flow-tip"><b>课堂提示</b><ul>{''.join(f'<li>{inline(x)}</li>' for x in (s.get('bullets') or ['按流程走通一遍，再回到自己的岗位，找出最容易出错的一步。'])[:3])}</ul></div><p class="flow-note">{esc(s.get('cap',''))}　完整彩色原理图见教材对应章节。</p>'''
            notes='按卡片顺序讲一遍流程：' + ' → '.join(s.get('steps',[])[:5]) + '……再让学员指出自己岗位在哪一步、最容易卡在哪一步。'
        elif t=='table':
            rows=s['rows']; head=''.join(f'<th>{inline(c)}</th>' for c in rows[0])
            bodyrows=''.join('<tr>'+''.join(f'<td>{inline(c)}</td>' for c in r)+'</tr>' for r in rows[1:])
            body=f'''<div class="slide-head">{kicker_html}<h2>{esc(s['title'])}</h2></div>
<div class="table-wrap"><table><thead><tr>{head}</tr></thead><tbody>{bodyrows}</tbody></table></div>'''
            notes='对照表格讲：' + '；'.join(' / '.join(r) for r in s.get('rows',[[]])[1:3]) + '。请学员找出自己岗位最常遇到的一行。'
        elif t=='quiz':
            ans=s.get('answers',[])
            items=''.join(f'<details class="q"><summary><span>{i:02d}</span>{inline(x)}</summary><div class="ans">{inline(ans[i-1]) if i-1<len(ans) else "请结合本课内容，按“判断依据 + 处置动作”作答。"}</div></details>' for i,x in enumerate(s['items'],1))
            body=f'<div class="slide-head"><div class="kicker">形成性评价</div><h2>{esc(s["title"])}</h2></div><div class="quiz-list">{items}</div>'
            notes='先独立作答 3 分钟，再两人互评，最后讲师点评。答案要点见教材“答案要点”。'
        elif t=='summary':
            red=''.join(f'<li>{inline(x)}</li>' for x in s['redlines'])
            body=f'''<div class="slide-head"><div class="kicker">收束</div><h2>{esc(s['title'])}</h2></div>
<div class="summary-grid"><div class="red"><h3>三条红线</h3><ul>{red}</ul></div><div class="hw"><h3>课后任务</h3><p>{esc(s['homework'])}</p></div></div>'''
            notes='让每位学员复述一条红线，并写下回岗后的第一个动作。'
        else:
            body=f'<div class="end-wrap"><h1>{esc(s["title"])}</h1><p>{esc(s["subtitle"])}</p><div class="brand">AI 实训舱 · 运营单位培训</div></div>'
            notes='结束：提醒教材、课件、演练任务单的位置。'
        out.append(f'''<section class="slide {t}" data-index="{idx}">
{body}
<div class="slide-footer"><span>{esc(deck_title)}</span><span>{idx:02d} / {len(slides):02d}</span></div>
<aside class="notes">{esc(notes)}</aside>
</section>''')
    return '\n'.join(out)

CSS = r'''
:root{--accent:%ACCENT%;--accent2:%ACCENT2%;--ink:#0F172A;--muted:#64748B;--bg:#F8FAFC;--line:#E2E8F0}
*{box-sizing:border-box;margin:0;padding:0}
html,body{height:100%;background:#0B1220;font-family:"Noto Sans CJK SC","Microsoft YaHei","PingFang SC",system-ui,sans-serif;color:var(--ink)}
body{overflow:hidden}
.deck{position:fixed;inset:0;display:flex;align-items:center;justify-content:center}
.slide{position:absolute;width:1280px;height:720px;background:var(--bg);overflow:hidden;display:none;padding:54px 64px 58px;box-shadow:0 30px 80px rgba(0,0,0,.35)}
.slide.active{display:block}
.slide::before{content:"";position:absolute;left:0;top:0;width:100%;height:7px;background:linear-gradient(90deg,var(--accent),var(--accent2))}
.slide-footer{position:absolute;left:64px;right:64px;bottom:20px;display:flex;justify-content:space-between;font-size:12px;color:var(--muted);letter-spacing:.04em}
.slide-footer span:first-child{text-transform:uppercase}
h1{font-size:58px;line-height:1.15;letter-spacing:-.02em}
h2{font-size:34px;line-height:1.25;letter-spacing:-.01em}
h3{font-size:20px;color:var(--accent);margin-bottom:10px}
p,li{font-size:19px;line-height:1.65}
.slide-head{margin-bottom:26px}
.kicker{font-size:13px;font-weight:700;letter-spacing:.12em;color:var(--accent);text-transform:uppercase;margin-bottom:8px}
.cover{background:linear-gradient(135deg,#0B1B33 0%,#12304F 55%,#0F3D3B 100%);color:#fff;padding:0}
.cover::before{height:0}
.cover-bg{position:absolute;inset:0;background:radial-gradient(900px 500px at 78% 18%,rgba(56,189,248,.28),transparent 60%),radial-gradient(700px 420px at 12% 88%,rgba(20,184,166,.24),transparent 60%)}
.cover-content{position:relative;z-index:2;padding:78px 84px;height:100%;display:flex;flex-direction:column;justify-content:center}
.brand{font-size:14px;letter-spacing:.18em;color:#94E2D5;font-weight:700;margin-bottom:22px}
.cover h1{font-size:66px;max-width:1000px;text-shadow:0 8px 30px rgba(0,0,0,.3)}
.cover .sub{font-size:22px;color:#CBD5E1;margin-top:16px}
.chips{display:flex;gap:10px;flex-wrap:wrap;margin-top:26px}
.chips span{background:rgba(255,255,255,.12);border:1px solid rgba(255,255,255,.2);color:#E2E8F0;padding:8px 14px;border-radius:999px;font-size:14px}
.cover-meta{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:10px 26px;margin-top:42px;max-width:820px}
.cover-meta div{display:flex;gap:12px;border-top:1px solid rgba(255,255,255,.16);padding-top:8px;font-size:13px}
.cover-meta b{color:#94E2D5;min-width:74px}.cover-meta span{color:#CBD5E1}
.case{background:linear-gradient(135deg,#0B1B33,#12304F);color:#fff;align-items:center}
.case.active{display:flex}
.case::before{height:0}
.case-wrap{max-width:980px}
.case-wrap .kicker{color:#94E2D5}
.case-wrap h2{font-size:44px;margin-bottom:22px}
.case-wrap blockquote{font-size:24px;line-height:1.65;color:#DBEAFE;border-left:5px solid #38BDF8;padding-left:22px}
.case-ask{margin-top:30px;display:flex;gap:14px;align-items:center;color:#94A3B8;font-size:15px}
.case-ask b{background:rgba(255,255,255,.1);color:#fff;padding:8px 12px;border-radius:999px;font-size:13px}
.obj-grid{display:grid;grid-template-columns:1fr 1fr;gap:16px}
.obj{display:flex;gap:16px;background:#fff;border:1px solid var(--line);border-radius:16px;padding:20px 22px;box-shadow:0 6px 18px rgba(15,23,42,.05)}
.obj span{font-size:26px;font-weight:800;color:var(--accent);line-height:1}
.obj p{font-size:18px;line-height:1.55}
.agenda-grid{display:grid;grid-template-columns:1fr 1fr;gap:14px}
.agenda-item{display:flex;gap:14px;align-items:flex-start;background:#fff;border:1px solid var(--line);border-radius:14px;padding:16px 18px}
.agenda-item span{font-size:15px;font-weight:800;color:#fff;background:var(--accent);border-radius:8px;padding:4px 8px}
.agenda-item p{font-size:18px}
.section{background:linear-gradient(135deg,#0B1B33,#12304F);color:#fff;display:none;align-items:center}
.section.active{display:flex}
.section::before{height:0}
.section-wrap{display:flex;gap:40px;align-items:center;padding:0 90px;width:100%}
.section-num{font-size:150px;font-weight:900;line-height:.85;color:rgba(148,226,213,.25);letter-spacing:-.06em}
.section h2{font-size:48px;max-width:780px}
.section .lead{color:#CBD5E1;font-size:20px;margin-top:14px;max-width:720px}
.section .kicker{color:#94E2D5}
.two-col{display:grid;grid-template-columns:1fr 1.1fr;gap:28px;align-items:start}
.two-col.flip{grid-template-columns:1.1fr 1fr}
.two-col.screen{grid-template-columns:.62fr 1.55fr}
.two-col.screen .shot img{max-height:500px;object-fit:contain}
.two-col.screen .text li{font-size:16px}
.two-col.phone{grid-template-columns:1.15fr .85fr;align-items:center}
.two-col.phone .text li{font-size:17px}
.two-col.phone .shot{width:300px;justify-self:center;border-radius:26px;border:6px solid #0F172A}
.two-col.phone .shot img{max-height:520px;object-fit:contain;background:#F8FAFC}
.two-col.phone .shot figcaption{display:none}
.two-col.flip .text{order:2}.two-col.flip figure{order:1}
.big-list{list-style:none}
.big-list li{position:relative;padding-left:24px;margin-bottom:12px;font-size:19px}
.big-list li::before{content:"";position:absolute;left:0;top:11px;width:8px;height:8px;border-radius:2px;background:var(--accent)}
.text ul{list-style:none}
.text li{position:relative;padding-left:24px;margin-bottom:11px;font-size:17.5px;line-height:1.55}
.text li::before{content:"";position:absolute;left:0;top:10px;width:7px;height:7px;border-radius:2px;background:var(--accent)}
.shot{background:#fff;border:1px solid var(--line);border-radius:14px;overflow:hidden;box-shadow:0 16px 40px rgba(15,23,42,.12);margin:0}
.shot img{display:block;width:100%;height:auto;max-height:430px;object-fit:contain;object-position:top;background:#fff}
.shot figcaption{font-size:12.5px;color:var(--muted);padding:9px 12px;border-top:1px solid var(--line);background:#fff}
.callout{margin-top:16px;background:#FFF7ED;border-left:5px solid #F59E0B;padding:14px 16px;border-radius:0 10px 10px 0;font-size:16px;color:#7C2D12}
.content-body{max-width:1050px}
.wide-chips{display:flex;gap:10px;flex-wrap:wrap;margin:0 0 12px}
.wide-chips span{font-size:13px;background:#EFF6FF;color:#1E3A8A;border:1px solid #BFDBFE;padding:6px 10px;border-radius:999px}
.wide-shot{max-width:100%}
.wide-shot img{max-height:420px;object-fit:contain}
.flow-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:12px}
.flow-card{background:#fff;border:1px solid var(--line);border-radius:12px;padding:14px 14px 12px;position:relative;min-height:84px;box-shadow:0 4px 14px rgba(15,23,42,.04)}
.flow-card b{display:inline-block;font-size:12px;color:#fff;background:var(--accent);border-radius:6px;padding:2px 6px;margin-bottom:8px}
.flow-card span{display:block;font-size:15px;line-height:1.45}
.flow-note{margin-top:8px;font-size:12px;color:var(--muted)}
.flow-tip{margin-top:16px;background:#FFF7ED;border-left:5px solid #F59E0B;border-radius:0 10px 10px 0;padding:10px 14px;display:flex;gap:14px;align-items:flex-start}
.flow-tip b{font-size:12px;color:#B45309;white-space:nowrap;padding-top:2px}
.flow-tip ul{list-style:none;display:flex;gap:22px;flex-wrap:wrap}
.flow-tip li{font-size:13px;color:#7C2D12}
.flow-tip li::before{content:'·';margin-right:6px;font-weight:900}
.table-wrap{overflow:hidden;border:1px solid var(--line);border-radius:14px;background:#fff}
table{width:100%;border-collapse:collapse}
th{background:#EFF6FF;color:#1E3A8A;font-size:14px;text-align:left;padding:10px 12px;border-bottom:1px solid var(--line)}
td{font-size:14px;padding:9px 12px;border-bottom:1px solid #F1F5F9;vertical-align:top}
tr:last-child td{border-bottom:0}
.quiz-list{display:grid;grid-template-columns:1fr 1fr;gap:12px}
.q{background:#fff;border:1px solid var(--line);border-radius:12px;padding:14px 16px}
.q summary{cursor:pointer;font-size:16px;line-height:1.5;list-style:none;display:flex;gap:10px}
.q summary::-webkit-details-marker{display:none}
.q summary span{font-weight:800;color:var(--accent)}
.q .ans{margin-top:10px;padding-top:10px;border-top:1px dashed var(--line);font-size:13.5px;color:var(--muted)}
.summary-grid{display:grid;grid-template-columns:1.2fr .8fr;gap:24px}
.red,.hw{background:#fff;border:1px solid var(--line);border-radius:16px;padding:24px}
.red ul{list-style:none}.red li{position:relative;padding-left:22px;margin-bottom:10px;font-size:18px}
.red li::before{content:"!";position:absolute;left:0;top:1px;width:16px;height:16px;border-radius:50%;background:#FEE2E2;color:#B91C1C;font-size:12px;font-weight:800;text-align:center;line-height:16px}
.hw p{font-size:18px;line-height:1.7}
.end{background:linear-gradient(135deg,#0B1B33,#0F3D3B);color:#fff;display:none;align-items:center;justify-content:center;text-align:center}
.end.active{display:flex}
.end::before{height:0}
.end-wrap h1{font-size:72px}
.end-wrap p{color:#CBD5E1;font-size:22px;margin-top:14px}
.end-wrap .brand{margin-top:40px}
.notes{display:none}
.progress{position:fixed;left:0;top:0;height:3px;background:linear-gradient(90deg,var(--accent),var(--accent2));z-index:50;transition:width .2s}
.hud{position:fixed;right:18px;bottom:48px;z-index:60;display:flex;gap:10px;opacity:.45;transition:opacity .2s}
.hud:hover{opacity:1}
.hud button{background:rgba(255,255,255,.12);color:#fff;border:1px solid rgba(255,255,255,.18);border-radius:8px;padding:6px 12px;font-size:12px;cursor:pointer;white-space:nowrap}
.overview{position:fixed;inset:0;background:rgba(2,6,23,.94);z-index:100;display:none;padding:28px;overflow:auto}
.overview.on{display:block}
.overview h2{color:#fff;font-size:18px;margin-bottom:16px}
.ov-grid{display:grid;grid-template-columns:repeat(5,1fr);gap:10px}
.ov{border:1px solid rgba(255,255,255,.14);border-radius:8px;padding:10px;color:#CBD5E1;font-size:12px;cursor:pointer;background:rgba(255,255,255,.04);min-height:58px}
.ov b{display:block;color:#94E2D5;font-size:11px;margin-bottom:4px}
body.printing .slide{position:relative;display:block;page-break-after:always;box-shadow:none;margin:0 auto}
@media print{
 @page{size:1280px 720px;margin:0}
 body{overflow:visible;background:#fff}
 .deck{position:static;display:block}
 .slide{position:relative;display:block!important;page-break-after:always;box-shadow:none;margin:0;width:1280px!important;height:720px!important;transform:none!important}
 .hud,.progress,.overview{display:none!important}
 .notes{display:none!important}
}
'''

JS = r'''
const slides=[...document.querySelectorAll('.slide')];let cur=0,notesOn=false;
const progress=document.querySelector('.progress');
function fit(){const s=Math.min(innerWidth/1280,innerHeight/720);document.querySelectorAll('.slide').forEach(el=>{el.style.transform=`scale(${s})`;el.style.transformOrigin='center center'});}
function show(i){cur=Math.max(0,Math.min(slides.length-1,i));slides.forEach((s,k)=>s.classList.toggle('active',k===cur));progress.style.width=((cur+1)/slides.length*100)+'%';history.replaceState(null,'','#'+(cur+1));if(notesOn){const nb=document.querySelector('.notes-body');const n=slides[cur].querySelector('.notes');if(nb)nb.textContent=n?n.textContent:''}}
function next(){show(cur+1)} function prev(){show(cur-1)}
addEventListener('keydown',e=>{
 if(['ArrowRight','ArrowDown','PageDown',' '].includes(e.key)){e.preventDefault();next()}
 if(['ArrowLeft','ArrowUp','PageUp'].includes(e.key)){e.preventDefault();prev()}
 if(e.key==='Home'){show(0)} if(e.key==='End'){show(slides.length-1)}
 if(e.key.toLowerCase()==='o'){document.querySelector('.overview').classList.toggle('on')}
 if(e.key.toLowerCase()==='n'){notesOn=!notesOn;document.querySelector('.notes-panel').classList.toggle('on',notesOn);const n=slides[cur].querySelector('.notes');document.querySelector('.notes-body').textContent=n?n.textContent:'(无备注)'}
 if(e.key.toLowerCase()==='f'){if(!document.fullscreenElement)document.documentElement.requestFullscreen();else document.exitFullscreen()}
 if(e.key.toLowerCase()==='p'){window.print()}
});
addEventListener('resize',fit);fit();show(0);
// overview
const ov=document.querySelector('.overview');const grid=ov.querySelector('.ov-grid');
slides.forEach((s,i)=>{const b=document.createElement('div');b.className='ov';const t=s.querySelector('h1,h2');b.innerHTML=`<b>${String(i+1).padStart(2,'0')}</b>${t?t.textContent:''}`;b.onclick=()=>{show(i);ov.classList.remove('on')};grid.appendChild(b)});
// notes panel
const np=document.createElement('div');np.className='notes-panel';np.innerHTML='<div class="np-head">讲师备注 <button onclick="this.closest(\'.notes-panel\').classList.remove(\'on\')">×</button></div><div class="notes-body"></div>';document.body.appendChild(np);
// swipe
let sx=0;addEventListener('touchstart',e=>sx=e.touches[0].clientX);addEventListener('touchend',e=>{const dx=e.changedTouches[0].clientX-sx;if(Math.abs(dx)>50){dx<0?next():prev()}});
'''

def main():
    files=sorted(glob.glob(os.path.join(MD,'*.md')))
    for f in files:
        base=os.path.basename(f); mid=base[:3]
        if mid not in DECKS: continue
        slug,accent,accent2=DECKS[mid]
        title,meta,blocks=parse(f)
        slides=build_slides(title,meta,blocks,CASES.get(mid,''))
        body=render(slides,title,accent,accent2)
        css=CSS.replace('%ACCENT%',accent).replace('%ACCENT2%',accent2)
        page=f'''<!doctype html>
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>{esc(title)} · 培训课件</title>
<style>{css}</style></head>
<body>
<div class="progress"></div>
<div class="deck">
{body}
</div>
<div class="overview"><h2>幻灯片总览（点击跳转，按 O 关闭）　·　打印/导出 PDF：按 P</h2><div class="ov-grid"></div></div>
<div class="hud"><button onclick="prev()">←</button><button onclick="next()">→</button><button onclick="document.querySelector('.overview').classList.add('on')">总览 O</button></div>
<style>
.notes-panel{{position:fixed;left:0;right:0;bottom:0;max-height:34vh;overflow:auto;background:#0F172A;color:#E2E8F0;border-top:2px solid #38BDF8;z-index:120;display:none;padding:14px 20px 18px}}
.notes-panel.on{{display:block}}
.np-head{{font-size:12px;color:#94E2D5;letter-spacing:.08em;margin-bottom:8px;display:flex;justify-content:space-between}}
.np-head button{{background:none;border:0;color:#fff;font-size:18px;cursor:pointer}}
.notes-body{{font-size:14px;line-height:1.7;color:#CBD5E1;white-space:pre-wrap}}
</style>
<script>{JS}</script>
</body></html>'''
        out=os.path.join(OUT,slug+'.html')
        open(out,'w',encoding='utf-8').write(page)
        print('saved',out,'slides',len(slides))

if __name__=='__main__': main()
