# -*- coding: utf-8 -*-
"""把第 3 章 109 页课件内容切成 9 个分片源文件（供讲稿分片撰写）。

每个分片源文件 `_src/ch3-pN.src.md` 包含：
  - 本片页码范围、页数
  - 每页：页码锚点、建议标题、课件全部文字块（按版式阅读顺序）、表格（Markdown）、
    图片数量、PPT 备注（讲者备注，若有）
输出同时打印全片页码-标题清单，便于校验。
"""
import json
import os
import re

BASE = os.path.dirname(os.path.abspath(__file__))
SRC = os.path.join(BASE, '_conv3', '_data', 'slides.json')
OUT = os.path.join(BASE, '讲稿', '_src')
SHARDS = [(1, 13), (14, 26), (27, 39), (40, 52), (53, 65),
          (66, 78), (79, 91), (92, 104), (105, 109)]


def clean_title(s, idx):
    s = (s or '').strip().replace('\n', ' ')
    s = re.sub(r'\s+', ' ', s)
    if not s or len(s) > 34:
        s = (s[:34] if s else '第 %d 页' % idx)
    return s


def page_md(sl):
    t = ['### 【3.%d】%s' % (sl['index'], clean_title(sl['title'], sl['index'])), '']
    texts = sorted(sl['texts'], key=lambda x: (round(x['top'], 2), x['left']))
    seen = set()
    for x in texts:
        for ln in x.get('lines') or [x['text']]:
            ln = ln.strip()
            if ln and ln not in seen:
                seen.add(ln)
                t.append('- ' + ln)
    if sl['tables']:
        t.append('')
        t.append('**本页表格（Markdown）：**')
        for tb in sl['tables']:
            rows = tb.get('rows') if isinstance(tb, dict) else tb
            if not rows:
                continue
            for i, r in enumerate(rows):
                cells = [(c or '').replace('\n', ' ').strip() for c in r]
                t.append('| ' + ' | '.join(cells) + ' |')
                if i == 0:
                    t.append('|' + '---|' * len(cells))
            t.append('')
    if sl['notes']:
        t.append('')
        t.append('**PPT 讲者备注：** %s' % re.sub(r'\s+', ' ', sl['notes']).strip())
    if sl['pics']:
        t.append('')
        t.append('**本页图片 %d 张**（版式图，内容见上方文字）' % len(sl['pics']))
    return '\n'.join(t)


def main():
    d = json.load(open(SRC, encoding='utf-8'))
    slides = {s['index']: s for s in d['slides']}
    os.makedirs(OUT, exist_ok=True)
    print('全片 %d 页' % len(slides))
    for n, (a, b) in enumerate(SHARDS, 1):
        body = ['# 第 3 章 讲稿分片源数据　第 %d 片（课件第 %d–%d 页，共 %d 页）' % (n, a, b, b - a + 1),
                '', '> 本文件只含课件原始内容，供撰写讲稿用；请勿改动页码锚点。', '']
        for i in range(a, b + 1):
            if i in slides:
                body.append(page_md(slides[i]))
                body.append('')
        p = os.path.join(OUT, 'ch3-p%d.src.md' % n)
        open(p, 'w', encoding='utf-8').write('\n'.join(body))
        print('  ✓ %s（第 %d–%d 页，%d 字符）' % (os.path.basename(p), a, b, len('\n'.join(body))))
    print('\n页码-标题清单：')
    for i in sorted(slides):
        print('  【3.%d】%s' % (i, clean_title(slides[i]['title'], i)))


if __name__ == '__main__':
    main()
