#!/usr/bin/env python3
"""初设切片脚本（配合千问办公/WorkBuddy 等 AI 助手使用）。

把大体量初设 Word 按标题层级切成小 Markdown 文件，供 AI 逐片处理（避免大文件爆上下文）。

标准用法（AI 助手内的流程）:
    1. python3 slice_chushe.py 初设.docx 任意目录 --dry-run     # 速读：各层级标题数+样例，不写文件
    2. 与用户确认：切分层级 / 剔除小节 / 文件命名规则
    3. python3 slice_chushe.py 初设.docx 输出目录/ [参数]       # 确认后正式切分（仅一次）

参数:
    --level N        切分层级（默认 5，即按 H5 标题切；切文件名取 N-1 级作前缀）
    --skip 词1,词2   剔除小节的关键词（默认：必要性说明,业务逻辑描述,数据流定义,
                     功能架构图,工作目标,工作路径,工作成果；传 none 表示不剔除）
    --name-rule X    文件命名层级：only（仅本标题）/ parent（默认，含 1 级父标题）/
                     数字 N（含 N 级父标题，如 2→"祖父-父-本"）/ all（含全部上级标题）
    --module 关键词   只切标题含该关键词的切片
    --dry-run        只输出目录速读，不写任何文件
    --number         文件名加两位文档顺序号前缀（01-…），批量装配保证排序即原文顺序

规则:
    - 从 --level 级标题开始切：该级每个标题一个切片文件，到下一个同级标题为止
    - 剔除：标题名含 --skip 任一关键词的小节，连同其下内容整节删除
    - 切片内层级保留：本标题=1个#，每深一级+1个#
    - 正文段落与表格（转简文本）保留
"""
import json
import os
import re
import sys

from docx import Document
from docx.table import Table
from docx.text.paragraph import Paragraph

DEFAULT_SKIP = ["必要性说明", "业务逻辑描述", "数据流定义", "功能架构图",
                "工作目标", "工作路径", "工作成果"]


def head_level(p):
    if p.style and p.style.name.startswith("Heading"):
        try:
            return int(p.style.name.split()[-1])
        except ValueError:
            pass
    return 0


def table_to_text(t):
    rows = []
    for r in t.rows:
        rows.append("、".join(c.text.strip().replace("\n", " ") for c in r.cells))
    return "\n".join(rows)


def build_stream(doc):
    body = doc.element.body
    stream = []
    for child in body.iterchildren():
        tag = child.tag.split("}")[-1]
        if tag == "p":
            stream.append(("p", Paragraph(child, doc)))
        elif tag == "tbl":
            stream.append(("tbl", Table(child, doc)))
    return stream


def dry_run(stream, level):
    """目录速读：各层级标题统计 + 目标层级标题清单（含字符量）。不写文件。"""
    from collections import Counter
    hv = Counter()
    heads = []  # (idx, lvl, text)
    for i, (kind, obj) in enumerate(stream):
        if kind == "p":
            l = head_level(obj)
            if l and obj.text.strip():
                hv[l] += 1
                heads.append((i, l, obj.text.strip()))
    print("=== 目录速读（未写入任何文件）===")
    print("各层级标题数:", {f"H{l}": c for l, c in sorted(hv.items())})
    # 目标层级标题清单 + 各标题区间的近似字符量
    idxs = [(i, l, t) for i, l, t in heads if l == level]
    print(f"\n按 H{level} 切将产出 {len(idxs)} 个切片文件：")
    for k, (i, l, t) in enumerate(idxs):
        nxt = idxs[k + 1][0] if k + 1 < len(idxs) else len(stream)
        chars = sum(len(o.text) for kk, o in stream[i:nxt] if kk == "p")
        print(f"  H{level} [{t[:40]}]  ~{chars} 字符")
    print(f"\n默认剔除小节: {'、'.join(DEFAULT_SKIP)}")
    print("确认切分层级/剔除清单/命名规则后，去掉 --dry-run 正式切分。")


def main():
    args = sys.argv[1:]
    if len(args) < 2:
        print(__doc__); sys.exit(64)
    src, out_dir = args[0], args[1]
    level = 5
    if "--level" in args:
        level = int(args[args.index("--level") + 1])
    skip = DEFAULT_SKIP
    if "--skip" in args:
        v = args[args.index("--skip") + 1]
        skip = [] if v.lower() == "none" else [x.strip() for x in v.split(",") if x.strip()]
    name_rule = "parent"
    if "--name-rule" in args:
        name_rule = args[args.index("--name-rule") + 1]
    # 解析命名层级：only=0, parent=1, 数字N=N, all=全部上级
    if name_rule == "only":
        name_depth = 0
    elif name_rule == "parent":
        name_depth = 1
    elif name_rule == "all":
        name_depth = 999
    else:
        name_depth = int(name_rule)
    only = args[args.index("--module") + 1] if "--module" in args else None
    dry = "--dry-run" in args

    doc = Document(src)
    stream = build_stream(doc)

    if dry:
        dry_run(stream, level)
        return

    os.makedirs(out_dir, exist_ok=True)
    # 父级标题栈：维护每级的当前标题（供 parent 命名与模块过滤）
    parent_stack = {}
    n_slices = 0
    n_skipped = 0
    number = "--number" in args
    order_manifest = []

    def filter_slice(title, lines):
        """剔除：切片自身标题命中 skip→整片剔除(返回 None)；否则按标题分节，
        某节的标题命中 skip 关键词→整节剔除。正文内容命中不触发（防误删正常功能点）。首节恒留。"""
        nonlocal n_skipped
        if skip and any(kw in title for kw in skip):
            return None
        if not skip:
            return lines
        sections, cur_head, cur_body = [], None, []
        for ln in lines:
            if ln.startswith("#"):
                if cur_head is not None:
                    sections.append((cur_head, cur_body))
                cur_head, cur_body = ln, []
            elif cur_head is not None:
                cur_body.append(ln)
        if cur_head is not None:
            sections.append((cur_head, cur_body))
        kept = []
        for idx, (head, body) in enumerate(sections):
            if idx == 0:  # 切片标题所在首节恒留
                kept.append(head); kept.extend(body); continue
            head_text = head.lstrip("#").strip()
            if any(kw in head_text for kw in skip):
                n_skipped += 1
                continue
            kept.append(head); kept.extend(body)
        return kept

    i = 0
    N = len(stream)

    def write_slice(title, lines):
        nonlocal n_slices
        if not lines or not any(l.strip() for l in lines):
            return
        # 多级父子命名：从 level-1 往上取 name_depth 级祖先标题，按层级顺序拼接
        parts = []
        for lv in range(max(1, level - name_depth), level):
            anc = parent_stack.get(lv, "")
            if anc:
                parts.append(anc)
        parts.append(title)
        name = "-".join(parts)
        safe = re.sub(r'[/\\:*?"<>|]', "_", name).strip()
        # --number：文件名带文档顺序号前缀，保证文件排序=原文顺序（批量装配必用）
        fname = f"{n_slices + 1:02d}-{safe}" if number else safe
        with open(os.path.join(out_dir, fname + ".md"), "w", encoding="utf-8") as f:
            f.write("\n".join(lines).rstrip() + "\n")
        order_manifest.append(name)
        n_slices += 1

    while i < N:
        kind, obj = stream[i]
        if kind == "p":
            lvl = head_level(obj)
            text = obj.text.strip()
            if lvl and lvl < level and text:
                parent_stack[lvl] = text
                i += 1
                continue
            if lvl == level and text:
                if only and only not in text and only not in parent_stack.get(level - 1, ""):
                    i += 1
                    continue
                title = text
                lines = [f"# {title}"]
                j = i + 1
                while j < N:
                    k2, o2 = stream[j]
                    if k2 == "p":
                        l2 = head_level(o2)
                        t2 = o2.text.strip()
                        if l2 and l2 <= level and t2:
                            break  # 下一个同级或更高级标题：切片结束
                        if t2:
                            if l2 > level:  # 层级保留：本标题=#，每深一级+1
                                lines.append("#" * (l2 - level + 1) + " " + t2)
                            else:
                                lines.append(t2)
                        j += 1
                    elif k2 == "tbl":
                        tt = table_to_text(o2)
                        if tt.strip():
                            lines.append(tt)
                        j += 1
                    else:
                        j += 1
                kept = filter_slice(title, lines)
                if kept is None:
                    n_skipped += 1  # 切片自身标题命中：整片剔除
                else:
                    write_slice(title, kept)
                i = j
                continue
        i += 1

    json.dump(order_manifest, open(os.path.join(out_dir, "_order.json"), "w", encoding="utf-8"), ensure_ascii=False, indent=1)

    print("顺序清单 _order.json 已写出（批量装配按此顺序）")

    print(f"切片完成: {n_slices} 个文件 -> {out_dir}")
    print(f"剔除小节: {n_skipped} 处（关键词: {'、'.join(skip) if skip else '无'}）")


if __name__ == "__main__":
    main()
