build_docx.py 29.2 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855
#!/usr/bin/env python3
"""Build the Word snapshot for the boutique order lifecycle documentation."""

from __future__ import annotations

import argparse
import re
from pathlib import Path
from typing import Iterable

from PIL import Image
from docx import Document
from docx.enum.section import WD_ORIENT, WD_SECTION
from docx.enum.table import WD_CELL_VERTICAL_ALIGNMENT, WD_TABLE_ALIGNMENT
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
from docx.shared import Inches, Pt, RGBColor


ROOT = Path(__file__).resolve().parents[1]
README_PATH = ROOT / "README.md"
ACCEPTANCE_PATH = ROOT / "test-acceptance.md"
TRACE_PATH = ROOT / "prd-traceability.md"
ASSET_DIR = ROOT / "assets"

BASE_FONT = "Microsoft YaHei"
CODE_FONT = "Consolas"
INK = "0B2545"
BLUE = "2E74B5"
DARK_BLUE = "1F4D78"
MUTED = "526274"
TABLE_HEADER = "E8EEF5"
LIGHT = "F4F6F9"
CAUTION = "FFF7DD"
RISK = "FDECEC"
BORDER = "A7B4C2"

PORTRAIT_TABLE_DXA = 9360
LANDSCAPE_TABLE_DXA = 14112
TABLE_INDENT_DXA = 120
CELL_MARGIN_TOP_BOTTOM = 80
CELL_MARGIN_SIDE = 120

FIGURE_FILES = [
    "order-end-to-end.png",
    "work-order-state-machine.png",
    "submission-decision.png",
    "cancel-refund-correction.png",
    "construction-lifecycle.png",
]
FIGURE_CAPTIONS = [
    "图 1 订单端到端角色泳道",
    "图 2 工单状态机与页面路由",
    "图 3 提交校验与 API 决策",
    "图 4 撤销、退款与标记错误",
    "图 5 施工单创建与商品级履约",
]


def set_run_font(
    run,
    *,
    name: str = BASE_FONT,
    size: float | None = None,
    color: str | None = None,
    bold: bool | None = None,
    italic: bool | None = None,
) -> None:
    run.font.name = name
    run._element.get_or_add_rPr()
    rfonts = run._element.rPr.get_or_add_rFonts()
    rfonts.set(qn("w:ascii"), name)
    rfonts.set(qn("w:hAnsi"), name)
    rfonts.set(qn("w:eastAsia"), name)
    if size is not None:
        run.font.size = Pt(size)
    if color:
        run.font.color.rgb = RGBColor.from_string(color)
    if bold is not None:
        run.bold = bold
    if italic is not None:
        run.italic = italic


def set_style_font(style, name: str, size: float, color: str | None = None) -> None:
    style.font.name = name
    style.font.size = Pt(size)
    style._element.get_or_add_rPr()
    rfonts = style._element.rPr.get_or_add_rFonts()
    rfonts.set(qn("w:ascii"), name)
    rfonts.set(qn("w:hAnsi"), name)
    rfonts.set(qn("w:eastAsia"), name)
    if color:
        style.font.color.rgb = RGBColor.from_string(color)


def set_cell_shading(cell, fill: str) -> None:
    tc_pr = cell._tc.get_or_add_tcPr()
    shd = tc_pr.find(qn("w:shd"))
    if shd is None:
        shd = OxmlElement("w:shd")
        tc_pr.append(shd)
    shd.set(qn("w:fill"), fill)


def set_cell_margins(cell) -> None:
    tc_pr = cell._tc.get_or_add_tcPr()
    tc_mar = tc_pr.first_child_found_in("w:tcMar")
    if tc_mar is None:
        tc_mar = OxmlElement("w:tcMar")
        tc_pr.append(tc_mar)
    for side, value in (
        ("top", CELL_MARGIN_TOP_BOTTOM),
        ("bottom", CELL_MARGIN_TOP_BOTTOM),
        ("start", CELL_MARGIN_SIDE),
        ("end", CELL_MARGIN_SIDE),
    ):
        node = tc_mar.find(qn(f"w:{side}"))
        if node is None:
            node = OxmlElement(f"w:{side}")
            tc_mar.append(node)
        node.set(qn("w:w"), str(value))
        node.set(qn("w:type"), "dxa")


def set_repeat_table_header(row) -> None:
    tr_pr = row._tr.get_or_add_trPr()
    tbl_header = tr_pr.find(qn("w:tblHeader"))
    if tbl_header is None:
        tbl_header = OxmlElement("w:tblHeader")
        tr_pr.append(tbl_header)
    tbl_header.set(qn("w:val"), "true")


def set_table_geometry(table, widths_dxa: list[int], total_dxa: int) -> None:
    table.alignment = WD_TABLE_ALIGNMENT.LEFT
    table.autofit = False
    tbl_pr = table._tbl.tblPr

    tbl_w = tbl_pr.find(qn("w:tblW"))
    if tbl_w is None:
        tbl_w = OxmlElement("w:tblW")
        tbl_pr.append(tbl_w)
    tbl_w.set(qn("w:w"), str(total_dxa))
    tbl_w.set(qn("w:type"), "dxa")

    tbl_ind = tbl_pr.find(qn("w:tblInd"))
    if tbl_ind is None:
        tbl_ind = OxmlElement("w:tblInd")
        tbl_pr.append(tbl_ind)
    tbl_ind.set(qn("w:w"), str(TABLE_INDENT_DXA))
    tbl_ind.set(qn("w:type"), "dxa")

    layout = tbl_pr.find(qn("w:tblLayout"))
    if layout is None:
        layout = OxmlElement("w:tblLayout")
        tbl_pr.append(layout)
    layout.set(qn("w:type"), "fixed")

    borders = tbl_pr.find(qn("w:tblBorders"))
    if borders is None:
        borders = OxmlElement("w:tblBorders")
        tbl_pr.append(borders)
    for edge in ("top", "left", "bottom", "right", "insideH", "insideV"):
        node = borders.find(qn(f"w:{edge}"))
        if node is None:
            node = OxmlElement(f"w:{edge}")
            borders.append(node)
        node.set(qn("w:val"), "single")
        node.set(qn("w:sz"), "6")
        node.set(qn("w:color"), BORDER)

    grid = table._tbl.tblGrid
    for child in list(grid):
        grid.remove(child)
    for width in widths_dxa:
        col = OxmlElement("w:gridCol")
        col.set(qn("w:w"), str(width))
        grid.append(col)

    for row in table.rows:
        for index, cell in enumerate(row.cells):
            width = widths_dxa[index]
            tc_pr = cell._tc.get_or_add_tcPr()
            tc_w = tc_pr.find(qn("w:tcW"))
            if tc_w is None:
                tc_w = OxmlElement("w:tcW")
                tc_pr.append(tc_w)
            tc_w.set(qn("w:w"), str(width))
            tc_w.set(qn("w:type"), "dxa")
            cell.width = Inches(width / 1440)
            set_cell_margins(cell)


def add_page_field(paragraph) -> None:
    paragraph.alignment = WD_ALIGN_PARAGRAPH.RIGHT
    prefix = paragraph.add_run("第 ")
    set_run_font(prefix, size=9, color=MUTED)
    begin = OxmlElement("w:fldChar")
    begin.set(qn("w:fldCharType"), "begin")
    begin_run = paragraph.add_run()
    set_run_font(begin_run, size=9, color=MUTED)
    begin_run._r.append(begin)
    instruction = OxmlElement("w:instrText")
    instruction.set(qn("xml:space"), "preserve")
    instruction.text = " PAGE "
    instruction_run = paragraph.add_run()
    set_run_font(instruction_run, size=9, color=MUTED)
    instruction_run._r.append(instruction)
    separate = OxmlElement("w:fldChar")
    separate.set(qn("w:fldCharType"), "separate")
    separate_run = paragraph.add_run()
    set_run_font(separate_run, size=9, color=MUTED)
    separate_run._r.append(separate)
    display = paragraph.add_run("1")
    set_run_font(display, size=9, color=MUTED)
    end = OxmlElement("w:fldChar")
    end.set(qn("w:fldCharType"), "end")
    end_run = paragraph.add_run()
    set_run_font(end_run, size=9, color=MUTED)
    end_run._r.append(end)
    tail = paragraph.add_run(" 页")
    set_run_font(tail, size=9, color=MUTED)


def set_paragraph_bottom_border(paragraph, color: str = BORDER) -> None:
    p_pr = paragraph._p.get_or_add_pPr()
    p_bdr = p_pr.find(qn("w:pBdr"))
    if p_bdr is None:
        p_bdr = OxmlElement("w:pBdr")
        p_pr.append(p_bdr)
    bottom = p_bdr.find(qn("w:bottom"))
    if bottom is None:
        bottom = OxmlElement("w:bottom")
        p_bdr.append(bottom)
    bottom.set(qn("w:val"), "single")
    bottom.set(qn("w:sz"), "6")
    bottom.set(qn("w:space"), "4")
    bottom.set(qn("w:color"), color)


def set_section_furniture(section, content_width_dxa: int) -> None:
    section.header_distance = Inches(0.492)
    section.footer_distance = Inches(0.492)
    header = section.header
    header.is_linked_to_previous = False
    hp = header.paragraphs[0]
    hp.alignment = WD_ALIGN_PARAGRAPH.LEFT
    hp.paragraph_format.space_after = Pt(3)
    run = hp.add_run("精品升级订单全流程维护手册")
    set_run_font(run, size=9, color=MUTED, bold=True)
    run = hp.add_run("    SAAS+V5.8.4 · a8bb30c6")
    set_run_font(run, size=9, color=MUTED)
    set_paragraph_bottom_border(hp)

    footer = section.footer
    footer.is_linked_to_previous = False
    fp = footer.paragraphs[0]
    fp.paragraph_format.space_before = Pt(3)
    add_page_field(fp)


def configure_styles(document: Document) -> None:
    normal = document.styles["Normal"]
    set_style_font(normal, BASE_FONT, 11, INK)
    normal.paragraph_format.space_before = Pt(0)
    normal.paragraph_format.space_after = Pt(6)
    normal.paragraph_format.line_spacing = 1.25

    h1 = document.styles["Heading 1"]
    set_style_font(h1, BASE_FONT, 16, BLUE)
    h1.font.bold = True
    h1.paragraph_format.space_before = Pt(18)
    h1.paragraph_format.space_after = Pt(10)
    h1.paragraph_format.keep_with_next = True

    h2 = document.styles["Heading 2"]
    set_style_font(h2, BASE_FONT, 13, BLUE)
    h2.font.bold = True
    h2.paragraph_format.space_before = Pt(14)
    h2.paragraph_format.space_after = Pt(7)
    h2.paragraph_format.keep_with_next = True

    h3 = document.styles["Heading 3"]
    set_style_font(h3, BASE_FONT, 12, DARK_BLUE)
    h3.font.bold = True
    h3.paragraph_format.space_before = Pt(10)
    h3.paragraph_format.space_after = Pt(5)
    h3.paragraph_format.keep_with_next = True

    caption = document.styles["Caption"]
    set_style_font(caption, BASE_FONT, 9, MUTED)
    caption.font.italic = False
    caption.paragraph_format.space_before = Pt(4)
    caption.paragraph_format.space_after = Pt(8)
    caption.paragraph_format.keep_with_next = False


def configure_page(section, landscape: bool = False) -> int:
    if landscape:
        section.orientation = WD_ORIENT.LANDSCAPE
        section.page_width = Inches(11)
        section.page_height = Inches(8.5)
        section.top_margin = Inches(0.6)
        section.bottom_margin = Inches(0.6)
        section.left_margin = Inches(0.6)
        section.right_margin = Inches(0.6)
        set_section_furniture(section, LANDSCAPE_TABLE_DXA)
        return LANDSCAPE_TABLE_DXA
    section.orientation = WD_ORIENT.PORTRAIT
    section.page_width = Inches(8.5)
    section.page_height = Inches(11)
    section.top_margin = Inches(1)
    section.bottom_margin = Inches(1)
    section.left_margin = Inches(1)
    section.right_margin = Inches(1)
    set_section_furniture(section, PORTRAIT_TABLE_DXA)
    return PORTRAIT_TABLE_DXA


def max_xml_id(element, tag: str, attribute: str) -> int:
    values: list[int] = []
    for node in element.findall(qn(tag)):
        raw = node.get(qn(attribute))
        if raw and raw.isdigit():
            values.append(int(raw))
    return max(values, default=0)


def create_numbering(document: Document, num_fmt: str, text: str) -> int:
    numbering = document.part.numbering_part.element
    abstract_id = max_xml_id(numbering, "w:abstractNum", "w:abstractNumId") + 1
    num_id = max_xml_id(numbering, "w:num", "w:numId") + 1

    abstract = OxmlElement("w:abstractNum")
    abstract.set(qn("w:abstractNumId"), str(abstract_id))
    multi = OxmlElement("w:multiLevelType")
    multi.set(qn("w:val"), "singleLevel")
    abstract.append(multi)
    level = OxmlElement("w:lvl")
    level.set(qn("w:ilvl"), "0")
    start = OxmlElement("w:start")
    start.set(qn("w:val"), "1")
    level.append(start)
    fmt = OxmlElement("w:numFmt")
    fmt.set(qn("w:val"), num_fmt)
    level.append(fmt)
    lvl_text = OxmlElement("w:lvlText")
    lvl_text.set(qn("w:val"), text)
    level.append(lvl_text)
    justification = OxmlElement("w:lvlJc")
    justification.set(qn("w:val"), "left")
    level.append(justification)
    p_pr = OxmlElement("w:pPr")
    tabs = OxmlElement("w:tabs")
    tab = OxmlElement("w:tab")
    tab.set(qn("w:val"), "num")
    tab.set(qn("w:pos"), "540")
    tabs.append(tab)
    p_pr.append(tabs)
    indent = OxmlElement("w:ind")
    indent.set(qn("w:left"), "540")
    indent.set(qn("w:hanging"), "270")
    p_pr.append(indent)
    spacing = OxmlElement("w:spacing")
    spacing.set(qn("w:after"), "80")
    spacing.set(qn("w:line"), "300")
    spacing.set(qn("w:lineRule"), "auto")
    p_pr.append(spacing)
    level.append(p_pr)
    abstract.append(level)
    numbering.append(abstract)

    num = OxmlElement("w:num")
    num.set(qn("w:numId"), str(num_id))
    abstract_ref = OxmlElement("w:abstractNumId")
    abstract_ref.set(qn("w:val"), str(abstract_id))
    num.append(abstract_ref)
    numbering.append(num)
    return num_id


def apply_numbering(paragraph, num_id: int) -> None:
    p_pr = paragraph._p.get_or_add_pPr()
    num_pr = p_pr.find(qn("w:numPr"))
    if num_pr is None:
        num_pr = OxmlElement("w:numPr")
        p_pr.append(num_pr)
    ilvl = OxmlElement("w:ilvl")
    ilvl.set(qn("w:val"), "0")
    num_id_node = OxmlElement("w:numId")
    num_id_node.set(qn("w:val"), str(num_id))
    num_pr.append(ilvl)
    num_pr.append(num_id_node)
    paragraph.paragraph_format.space_after = Pt(4)
    paragraph.paragraph_format.line_spacing = 1.25


def clean_inline(value: str) -> str:
    value = value.replace("<br>", "\n").replace("<br/>", "\n")
    value = value.replace(r"\|", "|")
    value = re.sub(r"\[([^\]]+)\]\([^)]+\)", r"\1", value)
    value = value.replace("**", "").replace("__", "")
    value = value.replace("`", "")
    return value.strip()


INLINE_TOKEN_RE = re.compile(
    r"(`[^`]+`|\*\*[^*]+\*\*|\[[^\]]+\]\([^)]+\)|【PRD-[^】]+】)"
)


def add_inline_runs(paragraph, text: str, size: float | None = None) -> None:
    cursor = 0
    for match in INLINE_TOKEN_RE.finditer(text):
        if match.start() > cursor:
            run = paragraph.add_run(text[cursor : match.start()])
            set_run_font(run, size=size)
        token = match.group(0)
        if token.startswith("`"):
            run = paragraph.add_run(token[1:-1])
            set_run_font(run, name=CODE_FONT, size=(size or 11) - 0.5, color=DARK_BLUE)
        elif token.startswith("**"):
            run = paragraph.add_run(token[2:-2])
            set_run_font(run, size=size, bold=True)
        elif token.startswith("["):
            link_text = token[1 : token.index("]")]
            run = paragraph.add_run(link_text)
            set_run_font(run, size=size, color=BLUE)
            run.font.underline = True
        else:
            run = paragraph.add_run(token)
            set_run_font(run, size=size, color=DARK_BLUE)
        cursor = match.end()
    if cursor < len(text):
        run = paragraph.add_run(text[cursor:])
        set_run_font(run, size=size)


def add_callout(document: Document, text: str, fill: str = LIGHT, total_dxa: int = PORTRAIT_TABLE_DXA) -> None:
    table = document.add_table(rows=1, cols=1)
    set_repeat_table_header(table.rows[0])
    cell = table.cell(0, 0)
    set_cell_shading(cell, fill)
    cell.vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER
    paragraph = cell.paragraphs[0]
    paragraph.paragraph_format.space_before = Pt(4)
    paragraph.paragraph_format.space_after = Pt(4)
    paragraph.paragraph_format.line_spacing = 1.2
    add_inline_runs(paragraph, text)
    set_table_geometry(table, [total_dxa], total_dxa)
    document.add_paragraph().paragraph_format.space_after = Pt(0)


def add_cover(document: Document) -> None:
    section = document.sections[0]
    configure_page(section, landscape=False)

    spacer = document.add_paragraph()
    spacer.paragraph_format.space_after = Pt(70)

    kicker = document.add_paragraph()
    kicker.alignment = WD_ALIGN_PARAGRAPH.CENTER
    kicker.paragraph_format.space_after = Pt(16)
    run = kicker.add_run("SAAS+ 小程序 · 开发维护手册")
    set_run_font(run, size=11, color=BLUE, bold=True)

    title = document.add_paragraph()
    title.alignment = WD_ALIGN_PARAGRAPH.CENTER
    title.paragraph_format.space_after = Pt(10)
    run = title.add_run("精品升级订单全流程维护手册")
    set_run_font(run, size=28, color=INK, bold=True)

    subtitle = document.add_paragraph()
    subtitle.alignment = WD_ALIGN_PARAGRAPH.CENTER
    subtitle.paragraph_format.space_after = Pt(48)
    run = subtitle.add_run("新建 · 支付 · 撤销/退款 · 纠错 · 施工 · 出库 · 完工 · 返工")
    set_run_font(run, size=13.5, color=DARK_BLUE)

    table = document.add_table(rows=4, cols=2)
    metadata = [
        ("适用分支", "SAAS+V5.8.4"),
        ("代码分析基线", "a8bb30c6"),
        ("生成日期", "2026-07-29"),
        ("事实口径", "当前代码为已上线现状;PRD 为业务背景和目标依据"),
    ]
    for row, (label, value) in zip(table.rows, metadata):
        row.cells[0].text = label
        row.cells[1].text = value
        set_cell_shading(row.cells[0], TABLE_HEADER)
        for index, cell in enumerate(row.cells):
            cell.vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER
            for paragraph in cell.paragraphs:
                paragraph.paragraph_format.space_before = Pt(2)
                paragraph.paragraph_format.space_after = Pt(2)
                for run in paragraph.runs:
                    set_run_font(run, size=10.5, bold=(index == 0), color=INK)
    set_repeat_table_header(table.rows[0])
    set_table_geometry(table, [2700, 6660], PORTRAIT_TABLE_DXA)

    note = document.add_paragraph()
    note.alignment = WD_ALIGN_PARAGRAPH.CENTER
    note.paragraph_format.space_before = Pt(36)
    run = note.add_run("面向后续开发、联调、排障和业务规则复核")
    set_run_font(run, size=10, color=MUTED, italic=True)
    document.add_page_break()


def add_static_toc(
    document: Document,
    main_markdown: str,
    acceptance_markdown: str,
    trace_markdown: str,
) -> None:
    heading = document.add_paragraph("目录", style="Heading 1")
    heading.paragraph_format.space_before = Pt(0)
    topics: list[str] = []
    for markdown, prefix in (
        (main_markdown, ""),
        (acceptance_markdown, "测试验收 · "),
        (trace_markdown, "附录 · "),
    ):
        for line in markdown.splitlines():
            if line.startswith("## "):
                topics.append(prefix + clean_inline(line[3:]))
    bullet_id = create_numbering(document, "bullet", "•")
    for topic in topics:
        paragraph = document.add_paragraph()
        apply_numbering(paragraph, bullet_id)
        add_inline_runs(paragraph, topic, size=10)
    document.add_page_break()


def split_table_row(line: str) -> list[str]:
    placeholder = "\u0000"
    protected = line.strip().strip("|").replace(r"\|", placeholder)
    return [
        clean_inline(cell.replace(placeholder, "|"))
        for cell in protected.split("|")
    ]


def is_separator_row(cells: list[str]) -> bool:
    return bool(cells) and all(re.fullmatch(r":?-{3,}:?", cell.strip()) for cell in cells)


def compute_widths(rows: list[list[str]], total_dxa: int) -> list[int]:
    column_count = max(len(row) for row in rows)
    max_lengths = [1] * column_count
    for row in rows:
        for index in range(column_count):
            value = row[index] if index < len(row) else ""
            lines = value.splitlines() or [""]
            max_lengths[index] = max(max_lengths[index], max(len(line) for line in lines))
    weights = [min(max(length, 6), 42) for length in max_lengths]
    weight_total = sum(weights)
    raw = [max(720, int(total_dxa * weight / weight_total)) for weight in weights]
    current = sum(raw)
    if current != total_dxa:
        raw[-1] += total_dxa - current
    if raw[-1] < 720:
        deficit = 720 - raw[-1]
        raw[-1] = 720
        widest = max(range(len(raw) - 1), key=lambda index: raw[index])
        raw[widest] -= deficit
    return raw


def add_markdown_table(
    document: Document,
    rows: list[list[str]],
    total_dxa: int,
    compact: bool,
) -> None:
    if not rows:
        return
    column_count = max(len(row) for row in rows)
    normalized = [row + [""] * (column_count - len(row)) for row in rows]
    table = document.add_table(rows=len(normalized), cols=column_count)
    widths = compute_widths(normalized, total_dxa)
    for row_index, row in enumerate(normalized):
        for column_index, value in enumerate(row):
            cell = table.cell(row_index, column_index)
            cell.text = ""
            cell.vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER
            if row_index == 0:
                set_cell_shading(cell, TABLE_HEADER)
            paragraph = cell.paragraphs[0]
            paragraph.paragraph_format.space_before = Pt(1)
            paragraph.paragraph_format.space_after = Pt(1)
            paragraph.paragraph_format.line_spacing = 1.1
            if (
                row_index > 0
                and normalized[0][column_index].strip().upper() == "SHA-256"
                and len(value.replace("`", "")) == 64
            ):
                value = value[:32] + "\n" + value[32:]
            run = paragraph.add_run(value)
            is_hash = normalized[0][column_index].strip().upper() == "SHA-256"
            set_run_font(
                run,
                name=CODE_FONT if is_hash else BASE_FONT,
                size=7.5 if (compact and is_hash) else (8.2 if compact else 9.2),
                color=INK,
                bold=(row_index == 0),
            )
            if column_count <= 4 and column_index == 0:
                paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
    set_repeat_table_header(table.rows[0])
    set_table_geometry(table, widths, total_dxa)
    document.add_paragraph().paragraph_format.space_after = Pt(0)


def set_image_alt_text(shape, description: str) -> None:
    doc_pr = shape._inline.docPr
    doc_pr.set("descr", description)
    doc_pr.set("title", description)


def add_figure(document: Document, index: int) -> None:
    image_path = ASSET_DIR / FIGURE_FILES[index]
    if not image_path.exists():
        raise FileNotFoundError(image_path)
    with Image.open(image_path) as image:
        width_px, height_px = image.size
    max_width = 6.1
    max_height = 7.4
    width_inches = min(max_width, max_height * width_px / height_px)
    paragraph = document.add_paragraph()
    paragraph.paragraph_format.page_break_before = True
    paragraph.paragraph_format.keep_with_next = True
    paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
    run = paragraph.add_run()
    shape = run.add_picture(str(image_path), width=Inches(width_inches))
    set_image_alt_text(shape, FIGURE_CAPTIONS[index])
    caption = document.add_paragraph(FIGURE_CAPTIONS[index], style="Caption")
    caption.alignment = WD_ALIGN_PARAGRAPH.CENTER


def add_code_block(document: Document, lines: list[str]) -> None:
    table = document.add_table(rows=1, cols=1)
    set_repeat_table_header(table.rows[0])
    cell = table.cell(0, 0)
    set_cell_shading(cell, LIGHT)
    paragraph = cell.paragraphs[0]
    paragraph.paragraph_format.space_before = Pt(4)
    paragraph.paragraph_format.space_after = Pt(4)
    paragraph.paragraph_format.line_spacing = 1.05
    run = paragraph.add_run("\n".join(lines))
    set_run_font(run, name=CODE_FONT, size=8.5, color=INK)
    set_table_geometry(table, [PORTRAIT_TABLE_DXA], PORTRAIT_TABLE_DXA)


def parse_markdown(
    document: Document,
    markdown: str,
    *,
    trace_appendix: bool,
    bullet_num_id: int,
    decimal_num_id: int,
    landscape_tables: bool | None = None,
    title_override: str | None = None,
) -> None:
    lines = markdown.splitlines()
    index = 0
    figure_index = 0
    use_landscape_tables = (
        trace_appendix if landscape_tables is None else landscape_tables
    )
    total_dxa = LANDSCAPE_TABLE_DXA if use_landscape_tables else PORTRAIT_TABLE_DXA
    first_title_seen = False

    while index < len(lines):
        line = lines[index].rstrip()
        if not line.strip():
            index += 1
            continue

        if line.startswith("```"):
            language = line[3:].strip().lower()
            block: list[str] = []
            index += 1
            while index < len(lines) and not lines[index].startswith("```"):
                block.append(lines[index])
                index += 1
            index += 1
            if language == "mermaid":
                add_figure(document, figure_index)
                figure_index += 1
            else:
                add_code_block(document, block)
            continue

        if line.startswith("# "):
            title_text = clean_inline(line[2:])
            if not first_title_seen:
                first_title_seen = True
                if title_override:
                    paragraph = document.add_paragraph(title_override, style="Heading 1")
                    paragraph.paragraph_format.space_before = Pt(0)
                elif trace_appendix:
                    paragraph = document.add_paragraph(
                        "附录:PRD 追溯矩阵与需求—代码偏差清单",
                        style="Heading 1",
                    )
                    paragraph.paragraph_format.space_before = Pt(0)
                index += 1
                continue
            document.add_paragraph(title_text, style="Heading 1")
            index += 1
            continue
        if line.startswith("## "):
            document.add_paragraph(clean_inline(line[3:]), style="Heading 1")
            index += 1
            continue
        if line.startswith("### "):
            document.add_paragraph(clean_inline(line[4:]), style="Heading 2")
            index += 1
            continue
        if line.startswith("#### "):
            document.add_paragraph(clean_inline(line[5:]), style="Heading 3")
            index += 1
            continue

        if line.startswith(">"):
            quote_lines: list[str] = []
            while index < len(lines) and lines[index].lstrip().startswith(">"):
                quote_lines.append(lines[index].lstrip()[1:].strip())
                index += 1
            add_callout(document, "\n".join(quote_lines), LIGHT, total_dxa)
            continue

        if line.startswith("|"):
            table_lines: list[list[str]] = []
            while index < len(lines) and lines[index].lstrip().startswith("|"):
                cells = split_table_row(lines[index])
                if not is_separator_row(cells):
                    table_lines.append(cells)
                index += 1
            add_markdown_table(
                document,
                table_lines,
                total_dxa,
                compact=trace_appendix,
            )
            continue

        bullet_match = re.match(r"^\s*-\s+(.*)$", line)
        if bullet_match:
            paragraph = document.add_paragraph()
            apply_numbering(paragraph, bullet_num_id)
            add_inline_runs(paragraph, bullet_match.group(1))
            index += 1
            continue

        numbered_match = re.match(r"^\s*\d+\.\s+(.*)$", line)
        if numbered_match:
            paragraph = document.add_paragraph()
            apply_numbering(paragraph, decimal_num_id)
            add_inline_runs(paragraph, numbered_match.group(1))
            index += 1
            continue

        paragraph_lines = [line]
        index += 1
        while index < len(lines):
            next_line = lines[index].rstrip()
            if (
                not next_line.strip()
                or next_line.startswith(("#", ">", "|", "```"))
                or re.match(r"^\s*-\s+", next_line)
                or re.match(r"^\s*\d+\.\s+", next_line)
            ):
                break
            paragraph_lines.append(next_line)
            index += 1
        paragraph = document.add_paragraph()
        add_inline_runs(paragraph, " ".join(part.strip() for part in paragraph_lines))

    if figure_index and figure_index != len(FIGURE_FILES):
        raise ValueError(f"Expected {len(FIGURE_FILES)} figures, inserted {figure_index}")


def set_document_properties(document: Document) -> None:
    props = document.core_properties
    props.title = "精品升级订单全流程维护手册"
    props.subject = "SAAS+ 小程序精品升级订单生命周期"
    props.author = ""
    props.last_modified_by = ""
    props.keywords = "订单,工单,施工单,出库,返工,维护手册"
    props.comments = "Markdown/Mermaid 为维护源,Word 为发布快照"


def build(output: Path) -> None:
    main_markdown = README_PATH.read_text(encoding="utf-8")
    acceptance_markdown = ACCEPTANCE_PATH.read_text(encoding="utf-8")
    trace_markdown = TRACE_PATH.read_text(encoding="utf-8")

    document = Document()
    configure_styles(document)
    set_document_properties(document)
    add_cover(document)
    add_static_toc(document, main_markdown, acceptance_markdown, trace_markdown)

    bullet_num_id = create_numbering(document, "bullet", "•")
    decimal_num_id = create_numbering(document, "decimal", "%1.")
    parse_markdown(
        document,
        main_markdown,
        trace_appendix=False,
        bullet_num_id=bullet_num_id,
        decimal_num_id=decimal_num_id,
    )

    landscape = document.add_section(WD_SECTION.NEW_PAGE)
    configure_page(landscape, landscape=True)
    parse_markdown(
        document,
        acceptance_markdown,
        trace_appendix=False,
        bullet_num_id=bullet_num_id,
        decimal_num_id=decimal_num_id,
        landscape_tables=True,
        title_override="测试验收:精品升级订单全流程自动化",
    )

    document.add_page_break()
    parse_markdown(
        document,
        trace_markdown,
        trace_appendix=True,
        bullet_num_id=bullet_num_id,
        decimal_num_id=decimal_num_id,
    )

    output.parent.mkdir(parents=True, exist_ok=True)
    document.save(output)
    print(f"Wrote {output}")


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--output",
        type=Path,
        default=ROOT / "精品升级订单全流程维护手册.docx",
    )
    args = parser.parse_args()
    build(args.output)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())