#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""从 提词器-合并版.html 抽出「逐字口播稿 + 对应画面/录屏清单」，合成一份 Markdown。
输出：提词器-文案对应画面.md
用法: python3 gen_script_pic_md.py
"""
import os, re, html as H

BASE = os.path.dirname(os.path.abspath(__file__))
SRC = os.path.join(BASE, '提词器-合并版.html')
OUT = os.path.join(BASE, '提词器-文案对应画面.md')


def flat(s):
    s = re.sub(r'<br\s*/?>', '\x00', s)
    s = re.sub(r'<[^>]+>', '', s)
    return H.unescape(s).replace('\u00a0', ' ').replace('\x00', '；').strip()


def parse_secs(h):
    out = []
    for m in re.finditer(r'<section class="sec"([^>]*)>([\s\S]*?)</section>', h):
        attrs, body = m.group(1), m.group(2)
        t = re.search(r'data-t="([^"]*)"', attrs)
        n = re.search(r'data-n="([^"]*)"', attrs)
        cum = re.search(r'data-cum="([^"]*)"', attrs)
        hd = re.search(r'<h2>([\s\S]*?)</h2>', body)
        ps = [flat(p) for p in re.findall(r'<p[^>]*>([\s\S]*?)</p>', body)]
        out.append({
            'title': flat(hd.group(1)) if hd else '',
            't': t.group(1) if t else '',
            'n': n.group(1) if n else '',
            'cum': cum.group(1) if cum else '',
            'paras': [p for p in ps if p],
        })
    return out


def parse_cards(h):
    out = []
    for m in re.finditer(r'<section class="card"[^>]*>([\s\S]*?)</section>', h):
        body = m.group(1)
        num = re.search(r'<span class="num">([\s\S]*?)</span>', body)
        hd = re.search(r'<h2>([\s\S]*?)</h2>', body)
        blocks = {}
        # h4 标题 + txt 内容成对出现
        for mm in re.finditer(r'<h4>([\s\S]*?)</h4>\s*<div class="[^"]*">([\s\S]*?)</div>', body):
            k = flat(mm.group(1))
            v = flat(mm.group(2))
            if v:
                blocks.setdefault(k, []).append(v)
        out.append({
            'num': flat(num.group(1)) if num else '',
            'title': flat(hd.group(1)) if hd else '',
            'blocks': blocks,
        })
    return out


def main():
    h = open(SRC, encoding='utf-8').read()
    secs = parse_secs(h)
    cards = parse_cards(h)
    assert len(secs) == len(cards), (len(secs), len(cards))

    L = []
    L.append('# 大全 · 通用 Agent 实战大课（提词器文案 + 对应画面）')
    L.append('')
    L.append('> 逐字口播稿，每一节下面跟着这一节要录的画面/录屏清单。')
    L.append('> 时长按实测语速分节估算；成片约 52 分钟。')
    L.append('')

    # 目录
    L.append('## 分节目录')
    L.append('')
    L.append('| # | 标题 | 纯念 | 字数 | 累计 |')
    L.append('|---|---|---|---|---|')
    for i, s in enumerate(secs, 1):
        L.append('| %d | %s | %s | %s | %s |' % (i, s['title'], s['t'], s['n'], s['cum']))
    L.append('')

    order = ['▶ 录什么', '◆ 画面怎么走', '✂ 剪辑要点', '◆ 动画', '⚠ 坑']
    for i, (s, c) in enumerate(zip(secs, cards), 1):
        L.append('---')
        L.append('')
        L.append('## %d. %s' % (i, s['title']))
        L.append('')
        L.append('**纯念 %s · %s 字 · 累计 %s**' % (s['t'], s['n'], s['cum']))
        L.append('')
        L.append('### 口播（逐字念）')
        L.append('')
        for p in s['paras']:
            L.append(p)
            L.append('')
        L.append('### 这一段画面怎么拍')
        L.append('')
        keys = [k for k in order if k in c['blocks']]
        for k in c['blocks']:
            if k not in keys:
                keys.append(k)
        for k in keys:
            L.append('**%s**' % k)
            L.append('')
            for v in c['blocks'][k]:
                L.append('- %s' % v)
            L.append('')

    open(OUT, 'w', encoding='utf-8').write('\n'.join(L))
    han = len(re.findall(r'[\u4e00-\u9fff]', '\n'.join(L)))
    print('写好', OUT, os.path.getsize(OUT), 'bytes', len(secs), '节', han, '汉字')


if __name__ == '__main__':
    main()
