# -*- coding: utf-8 -*-
"""由「拆页版」逐页识别结果生成第 3 章教材原文 MD。

页序依据：本批照片是**连续拍摄的跨页**，拆页序号与印刷页码严格对应
（页码 = 41 + 拆页序号，即书页 42–75），该关系已用 20 余处 VL 读出的页码交叉验证。

输出：
  <OUT>/第3章-软件测试方法-教材原文.md     —— 主体（逐页正文 + 章节结构表）
  <OUT>/第3章-软件测试方法-纯净全文.txt    —— 不带页码/页眉的连续正文
"""
import glob
import json
import os
import re

BASE = os.path.dirname(os.path.abspath(__file__))
BOOK = os.path.join(BASE, 'data', 'books',
                    '软件测试方法和技术第4版_第3章_软件测试方法_拆页版')
OUT = os.path.join(BASE, '第3章-成品')
PAGE0 = 41          # 页码 = PAGE0 + 拆页序号

HEADER_RE = re.compile(
    r'^\s*(?:第\s*3\s*章\s*软件测试方法\s*\d{2,3}|\d{2,3}\s*软件测试方法(?:和)?(?:技术|艺术)'
    r'[（(]第\s*[34]\s*版[)）]|软件测试方法(?:和)?(?:技术|艺术)[（(]第\s*[34]\s*版[)）])\s*$')
FOOTER_RE = re.compile(r'^\s*(?:第\s*3\s*章\s*软件测试方法\s*\d{2,3}|\d{2,3}\s*软件测试方法和技术[（(]第4版[)）])\s*$')
SEC_RE = re.compile(r'(?m)^\s*(\d\.\d(?:\.\d)?)\s*([^\n]{2,30}?)\s*$')

# 教材目录（OCR 自书本目录页，2026-09-09）——用于给出"教材标注页码"
TOC = os.path.join('/home/zyw/Downloads/dl-hub/25-软件测试方法和技术第4版OCR整理',
                   '第1篇 软件测试的原理与方法', '第3章 软件测试方法', '目录条目.md')
TOC_RE = re.compile(r'^\s*(\d\.\d(?:\.\d)?)\s+(.+?)(?:\s+(\d{1,3}))?\s*$', re.M)


def load_toc():
    if not os.path.exists(TOC):
        return []
    out = []
    for line in open(TOC, encoding='utf-8'):
        m = TOC_RE.match(line.strip())
        if m and m.group(1).startswith('3.'):
            out.append((m.group(1), m.group(2).strip(),
                        int(m.group(3)) if m.group(3) else None))
    return out


def load():
    rows = []
    for f in sorted(glob.glob(os.path.join(BOOK, '第*.vl.json'))):
        seq = int(os.path.basename(f)[1:4])
        d = json.load(open(f, encoding='utf-8'))
        rows.append({'seq': seq, 'page': PAGE0 + seq,
                     'header': (d.get('header') or '').strip(),
                     'footer': (d.get('footer') or '').strip(),
                     'body': (d.get('body') or '').strip()})
    return rows


def clean(body):
    """把混在正文首/尾的页眉页脚行摘出来（VL 有时把它们并入正文）。"""
    lines = [l.rstrip() for l in body.split('\n')]
    head = foot = ''
    if lines and HEADER_RE.match(lines[0]):
        head = lines.pop(0).strip()
    while lines and not lines[-1].strip():
        lines.pop()
    if lines and FOOTER_RE.match(lines[-1]):
        foot = lines.pop().strip()
    return head, '\n'.join(lines).strip(), foot


def main():
    rows = load()
    for r in rows:
        h, b, f = clean(r['body'])
        r['h'], r['b'], r['f'] = h, b, f
    os.makedirs(OUT, exist_ok=True)

    # 章节结构：以教材目录为准，逐条到正文里定位"标题实际出现在哪一页"
    toc = load_toc()
    found = {}      # 节号 -> 实际页
    for no, title, _tp in toc:
        # ① 先按节号找（允许行首带 #、* 等 Markdown 记号；负向断言避免 3.4 命中 3.4.2）
        pat = re.compile(r'(?m)^[\s#*>]*' + re.escape(no) + r'(?!\s*\.\d)\s*[^\n]{0,30}$')
        for r in rows:
            if pat.search(r['b']):
                found[no] = r['page']
                break
        if no in found:
            continue
        # ② 节号被识别错（如 3.4 读成 4、3.4.1 读成 4.1）或缺标题行时，改用标题文字找
        norm = lambda s: re.sub(r'[^\u4e00-\u9fffA-Za-z0-9]', '', s)
        key = norm(title)[:5]
        if len(key) >= 2:
            for r in rows:
                if key in norm(r['b']):
                    found[no] = r['page']
                    break
    o = []
    o.append('# 第 3 章　软件测试方法（教材原文）\n')
    o.append('> **教材**：《软件测试方法和技术》（第 4 版）　第 1 篇 软件测试的原理与方法 → 第 3 章')
    o.append('> **来源**：2026-10-08 拍摄的课本照片 17 张（每张为摊开的左右两面，其中 8 张旋转 90°、1 张整体倒置），')
    o.append('> 程序自动纠正方向并拆成单页 34 页后逐页识别（本地 RapidOCR + DeepSeek 结构化视觉模型）。')
    o.append('> **覆盖**：书页 **42–75**（本章完整，34 页；42 页为章首页、不印页码）；表格已还原为 Markdown。\n')
    o.append('## 一、本章结构（页码为教材印刷页）\n')
    o.append('| 节 | 标题 | 教材目录标注 | 正文实际页 |\n|---|---|---|---|')
    for no, title, tp in toc:
        o.append('| %s | %s | %s | %s |' % (no, title, tp if tp else '—',
                                          found.get(no, '—')))
    o.append('\n> 说明：教材目录页标注的起始页与正文实际印刷页**普遍相差 1–2 页**（目录 OCR 于 2026-09-09，')
    o.append('> 其中 3.5.1 之后几项原本就没有页号）。上表"正文实际页"由本次逐页识别的正文标题定位，**以印刷页码为准**。\n')
    o.append('\n---\n')
    o.append('## 二、逐页正文\n')
    for r in rows:
        o.append('\n### 第 %d 页\n' % r['page'])
        hdr = r['h'] or (r['header'] if r['header'] not in ('', '无') else '')
        ftr = r['f'] or (r['footer'] if r['footer'] not in ('', '无') else '')
        if hdr:
            o.append('`页眉：%s`\n' % hdr)
        o.append(r['b'] if r['b'] else '（本页未识别出文字）')
        if ftr and ftr != hdr:
            o.append('\n`页脚：%s`' % ftr)
        o.append('')
    md = '\n'.join(o).rstrip() + '\n'
    p = os.path.join(OUT, '第3章-软件测试方法-教材原文.md')
    open(p, 'w', encoding='utf-8').write(md)

    plain = '\n\n'.join(r['b'] for r in rows if r['b'])
    p2 = os.path.join(OUT, '第3章-软件测试方法-纯净全文.txt')
    open(p2, 'w', encoding='utf-8').write(plain + '\n')

    print('✓ %s（%d 字符，%d 页）' % (os.path.basename(p), len(md), len(rows)))
    print('✓ %s（%d 字符）' % (os.path.basename(p2), len(plain)))
    print('  章节条目 %d 个｜表格 %d 张｜正文合计 %d 字'
          % (len(toc), md.count('\n| ---'), sum(len(r['b']) for r in rows)))
    for no, title, tp in toc:
        print("    %-7s %-26s 目录%s → 实际%s" % (no, title, tp if tp else "—", found.get(no, "—")))


if __name__ == '__main__':
    main()
