#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""把《02-填空模板与真实词库.md》里的词库表按最新的 04-参数词库速查.md 重新对齐。

原因：04 的词频统计口径修过（OCR 断行导致的碎片行被归一化），旧数字会过期。
本脚本只改**数字**与表格排版，不改文档正文文字。
"""
import re, sys

BASE = "/home/zyw/Downloads/dl-hub/85-AI生图提示词知识库-桀克AIShotLab"
F04 = BASE + "/04-参数词库速查.md"
FDOC = BASE + "/01-方法论-五维参数框架/02-填空模板与真实词库.md"

# 1) 解析 04：section -> {word: count}
s04 = open(F04, encoding="utf-8").read()
lex, cur = {}, None
for line in s04.split("\n"):
    m = re.match(r"^## (.+)$", line)
    if m:
        cur = m.group(1).strip()
        lex.setdefault(cur, {})
        continue
    m = re.match(r"^\|\s*(.+?)\s*\|\s*(\d+)\s*\|\s*$", line)
    if m and cur and m.group(1) not in ("词",):
        lex[cur][m.group(1).strip()] = int(m.group(2))

doc = open(FDOC, encoding="utf-8").read()
lines = doc.split("\n")
out, i, changed, dropped, missing = [], 0, 0, [], []
while i < len(lines):
    line = lines[i]
    m = re.match(r"^### \d+\.\d+ (.+?)（04 §(.+)）\s*$", line)
    if not m:
        out.append(line)
        i += 1
        continue
    sec = m.group(2).strip()
    out.append(line)
    i += 1
    # 复制到表头之前的内容（空行、"数字照抄…"说明段）
    while i < len(lines) and not lines[i].startswith("|"):
        out.append(lines[i])
        i += 1
    if i >= len(lines):
        break
    # 收集原表的词序
    words = []
    while i < len(lines) and lines[i].startswith("|"):
        cells = [c.strip() for c in lines[i].strip().strip("|").split("|")]
        if not set("".join(cells)) <= set("-: "):
            for k in range(0, len(cells) - 1, 2):
                w = cells[k]
                if w and w != "词":
                    words.append(w)
        i += 1
    tbl = lex.get(sec, {})
    pairs = []
    for w in words:
        if w in tbl:
            pairs.append((w, tbl[w]))
        else:
            dropped.append((sec, w))
    if not pairs:
        out.append("（本节词库为空）")
        continue
    out.append("| 词 | 次数 | 词 | 次数 | 词 | 次数 |")
    out.append("|---|---:|---|---:|---|---:|")
    for k in range(0, len(pairs), 3):
        chunk = pairs[k:k + 3]
        row = []
        for w, c in chunk:
            row += [w, str(c)]
        while len(row) < 6:
            row += ["", ""]
        out.append("| " + " | ".join(row) + " |")
        changed += 1
    out.append("")

open(FDOC, "w", encoding="utf-8").write("\n".join(out))
print("已同步表格分节:", len([l for l in out if l.startswith('### ')]))
print("重写行数:", changed)
print("04 中已不存在、被丢弃的旧词条:", dropped if dropped else "无")
