#!/usr/bin/env python3
import argparse
import re
import shutil
import subprocess
import tempfile
import zipfile
from pathlib import Path

from lxml import etree


ROOT = Path(__file__).resolve().parents[1]
SRC = ROOT / "src"

NS = {
    "w": "http://schemas.openxmlformats.org/wordprocessingml/2006/main",
    "a": "http://schemas.openxmlformats.org/drawingml/2006/main",
    "wp": "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing",
    "r": "http://schemas.openxmlformats.org/officeDocument/2006/relationships",
}
W = "{%s}" % NS["w"]
R = "{%s}" % NS["r"]
PKG_REL_NS = "http://schemas.openxmlformats.org/package/2006/relationships"
XML_SPACE = "{http://www.w3.org/XML/1998/namespace}space"
PAGE_WIDTH = 11906
PAGE_HEIGHT = 16838
MARGIN_LEFT = 1417
MARGIN_RIGHT = 1417
MARGIN_TOP = 1440
MARGIN_BOTTOM = 1440
CONTENT_WIDTH = PAGE_WIDTH - MARGIN_LEFT - MARGIN_RIGHT


def read_expanded_body() -> str:
    body = (SRC / "body.tex").read_text(encoding="utf-8")

    def repl(match: re.Match) -> str:
        rel = match.group(1)
        path = ROOT / rel
        if not path.exists():
            path = SRC / rel
        return path.read_text(encoding="utf-8")

    text = re.sub(r"\\input\{([^}]+)\}", repl, body)
    text = re.sub(r"\\newcommand\{\\resultimage\}\[3\]\{.*?\\endgroup\s*\}", "", text, flags=re.S)
    return text


def read_abstract() -> tuple[str, list[str], str]:
    text = (SRC / "frontmatter" / "abstract.tex").read_text(encoding="utf-8")
    title_match = re.search(r"\\fontsize\{22bp\}\{33bp\}\\selectfont\s*([^\\]+?)\\par", text, re.S)
    title = strip_inline(title_match.group(1), {}) if title_match else "学院生活平台"
    keyword_match = re.search(r"\\noindent\\textbf\{关键词：\}(.+)", text)
    keywords = strip_inline(keyword_match.group(1), {}) if keyword_match else ""

    marker = r"\noindent{\kaishu\bfseries\sanhao 摘要：\par}"
    start = text.find(marker)
    end = keyword_match.start() if keyword_match else len(text)
    body = text[start + len(marker) : end] if start != -1 else ""
    body = re.sub(r"\\vspace(?:\*)?\{[^}]*\}", "", body)
    body = re.sub(r"\\phantomsection|\\addcontentsline\{[^}]+\}\{[^}]+\}\{[^}]+\}", "", body)

    paragraphs = []
    for part in re.split(r"\n\s*\n", body):
        paragraph = strip_inline(part, {})
        if paragraph:
            paragraphs.append(paragraph)
    return title, paragraphs, keywords


def read_toc_lines() -> list[tuple[str, str, int]]:
    toc = (ROOT / "build" / "main.toc").read_text(encoding="utf-8")
    lines = []
    for raw in toc.splitlines():
        m = re.match(r"\\contentsline \{([^}]+)\}\{(?:\\numberline \{([^}]*)\})?([^}]*)\}\{([^}]*)\}", raw)
        if not m:
            continue
        kind, number, title, page = m.groups()
        number = number or ""
        title = strip_inline(title, {})
        page = int(page) if page.isdigit() else 0
        if kind == "section" and title == "摘要":
            continue
        elif kind == "section":
            lines.append(("chapter", f"{number} {title}".strip(), page))
        elif kind == "subsection":
            lines.append(("section", f"{number} {title}".strip(), page))
        elif kind == "subsubsection":
            lines.append(("subsection", f"{number} {title}".strip(), page))
    return lines


def strip_inline(text: str, refs: dict[str, str]) -> str:
    text = text.replace("\u00a0", " ")
    text = re.sub(r"表~?\\ref\{([^}]+)\}", lambda m: refs.get(m.group(1), "表"), text)
    text = re.sub(r"图~?\\ref\{([^}]+)\}", lambda m: refs.get(m.group(1), "图"), text)
    text = re.sub(r"\\ref\{([^}]+)\}", lambda m: refs.get(m.group(1), ""), text)
    text = re.sub(r"\\label\{[^}]+\}", "", text)
    text = re.sub(r"\\codeid\{([^}]*)\}", r"\1", text)
    text = re.sub(r"\\textbf\{([^}]*)\}", r"\1", text)
    text = re.sub(r"\\url\{([^}]*)\}", r"\1", text)
    text = re.sub(r"\\emph\{([^}]*)\}", r"\1", text)
    text = text.replace(r"\%", "%").replace(r"\_", "_").replace(r"\&", "&")
    text = text.replace(r"\#", "#").replace(r"\$", "$")
    text = text.replace("~", " ")
    text = text.replace(r"\par", "")
    text = re.sub(r"\\[a-zA-Z]+\*?(?:\[[^\]]*\])?(?:\{[^}]*\})?", "", text)
    text = text.replace("{", "").replace("}", "")
    text = re.sub(r"\s+", " ", text)
    return text.strip()


def split_cells(row: str) -> list[str]:
    cells = []
    cur = []
    escaped = False
    for ch in row:
        if ch == "\\" and not escaped:
            escaped = True
            cur.append(ch)
            continue
        if ch == "&" and not escaped:
            cells.append("".join(cur).strip())
            cur = []
        else:
            cur.append(ch)
        escaped = False
    cells.append("".join(cur).strip())
    return cells


def collect_refs(text: str) -> dict[str, str]:
    refs: dict[str, str] = {}
    chapter = 0
    table_no = 0
    figure_no = 0
    pattern = re.compile(
        r"\\section\{[^}]+\}"
        r"|\\begin\{table\}\[H\].*?\\end\{table\}"
        r"|\\begin\{figure\}\[H\].*?\\end\{figure\}"
        r"|\\resultimage\s*\{[^}]+\}\s*\{[^}]+\}\s*\{[^}]+\}",
        re.S,
    )
    for match in pattern.finditer(text):
        block = match.group(0)
        if block.startswith(r"\section{"):
            chapter += 1
            table_no = 0
            figure_no = 0
            continue
        label = re.search(r"\\label\{([^}]+)\}", block)
        if block.startswith(r"\begin{table}"):
            table_no += 1
            if label:
                refs[label.group(1)] = f"表 {chapter}-{table_no}" if chapter else f"表 {table_no}"
        else:
            figure_no += 1
            if block.startswith(r"\resultimage"):
                args = re.findall(r"\{([^}]*)\}", block)
                if len(args) >= 2:
                    refs[args[1]] = f"图 {chapter}-{figure_no}" if chapter else f"图 {figure_no}"
            elif label:
                refs[label.group(1)] = f"图 {chapter}-{figure_no}" if chapter else f"图 {figure_no}"
    return refs


def markdown_table(rows: list[list[str]]) -> str:
    if not rows:
        return ""
    width = max(len(r) for r in rows)
    normalized = []
    for row in rows:
        row = row + [""] * (width - len(row))
        normalized.append([c.replace("|", r"\|") for c in row])
    header = normalized[0]
    body = normalized[1:]
    lines = [
        "| " + " | ".join(header) + " |",
        "| " + " | ".join(["---"] * width) + " |",
    ]
    for row in body:
        lines.append("| " + " | ".join(row) + " |")
    return "\n".join(lines)


def convert_table(block: str, number: str, refs: dict[str, str]) -> str:
    caption_match = re.search(r"\\caption\{([^}]*)\}", block)
    caption = strip_inline(caption_match.group(1), refs) if caption_match else f"表 {number}"
    rows: list[list[str]] = []
    in_tabular = False
    for raw in block.splitlines():
        stripped = raw.strip()
        if stripped.startswith(r"\begin{tabularx}"):
            in_tabular = True
            continue
        if stripped.startswith(r"\end{tabularx}"):
            in_tabular = False
            continue
        if in_tabular:
            line = raw.strip()
            if not line or line.startswith(r"\toprule") or line.startswith(r"\midrule") or line.startswith(r"\bottomrule"):
                continue
            line = line.replace(r"\theadrow", "").strip()
            if line.endswith(r"\\"):
                line = line[:-2].strip()
            if not line:
                continue
            rows.append([strip_inline(cell, refs) for cell in split_cells(line)])
    return f"\n表 {number}\u3000{caption}\n\n{markdown_table(rows)}\n"


def image_markdown(path: str, caption: str, number: str) -> str:
    path = path.strip()
    caption = caption.strip()
    return f"\n![](<{path}>){'{width=5.6in}'}\n\n图 {number}\u3000{caption}\n"


def convert_figure(block: str, number: str, refs: dict[str, str]) -> str:
    caption_match = re.search(r"\\caption\{([^}]*)\}", block)
    path_match = re.search(r"\\includegraphics(?:\[[^\]]*\])?\{([^}]+)\}", block)
    caption = strip_inline(caption_match.group(1), refs) if caption_match else f"图 {number}"
    path = path_match.group(1) if path_match else ""
    return image_markdown(path, caption, number)


def convert_resultimage(block: str, number: str, refs: dict[str, str]) -> str:
    args = re.findall(r"\{([^}]*)\}", block)
    if len(args) < 3:
        return ""
    caption = strip_inline(args[0], refs)
    return image_markdown(args[2], caption, number)


def chinese_chapter(n: int) -> str:
    chars = "零一二三四五六七八九十"
    if n <= 10:
        return chars[n]
    if n < 20:
        return "十" + chars[n - 10]
    return str(n)


def make_tab_run():
    run = etree.Element(qn("r"))
    etree.SubElement(run, qn("tab"))
    return run


def build_static_toc(lines: list[tuple[str, str, int]]):
    nodes = [make_paragraph([("目录", "30", True, "黑体")], "TOCHeading", "center")]
    for level, text, page in lines:
        if level == "chapter":
            style = "TOC1"
        elif level == "section":
            style = "TOC2"
        else:
            style = "TOC3"
        p = etree.Element(qn("p"))
        set_paragraph_style(p, style)
        ppr = p.find(qn("pPr"))
        tabs = set_child(ppr, "tabs")
        for old in list(tabs):
            tabs.remove(old)
        tab = etree.SubElement(tabs, qn("tab"))
        tab.set(qn("val"), "right")
        tab.set(qn("leader"), "dot")
        tab.set(qn("pos"), str(CONTENT_WIDTH))
        p.append(make_run(text, "28", False, "黑体" if style == "TOC1" else ("楷体" if style == "TOC3" else "宋体")))
        p.append(make_tab_run())
        p.append(make_run(str(page), "28", False, "宋体"))
        nodes.append(p)
    nodes.append(make_page_break())
    return nodes


def convert_tex_to_markdown(text: str) -> str:
    refs = collect_refs(text)
    output: list[str] = []
    para: list[str] = []
    chapter = section = subsection = 0
    table_no = figure_no = 0
    skipping_macro = False

    def flush_para() -> None:
        if para:
            joined = strip_inline(" ".join(para), refs)
            if joined:
                output.append(joined)
                output.append("")
            para.clear()

    block_pattern = re.compile(
        r"\\begin\{table\}\[H\].*?\\end\{table\}"
        r"|\\begin\{figure\}\[H\].*?\\end\{figure\}"
        r"|\\resultimage\s*\{[^}]+\}\s*\{[^}]+\}\s*\{[^}]+\}",
        re.S,
    )
    pos = 0
    for match in block_pattern.finditer(text):
        before = text[pos:match.start()]
        for line in before.splitlines():
            stripped = line.strip()
            if stripped.startswith(r"\newcommand{\resultimage}"):
                skipping_macro = True
                continue
            if skipping_macro:
                if stripped == "}":
                    skipping_macro = False
                continue
            if not stripped:
                flush_para()
                continue
            if stripped.startswith("%"):
                continue
            if stripped.startswith(r"\clearpage") or stripped.startswith(r"\phantomsection") or stripped.startswith(r"\addcontentsline"):
                continue
            if stripped.startswith(r"\begingroup") or stripped.startswith(r"\endgroup") or stripped.startswith(r"\sloppy"):
                continue
            if stripped.startswith(r"\setlength") or stripped.startswith(r"\hangindent") or stripped.startswith(r"\hangafter"):
                continue
            if stripped == r"\wuhao":
                continue

            m = re.match(r"\\section\{([^}]+)\}", stripped)
            if m:
                flush_para()
                chapter += 1
                section = subsection = 0
                table_no = figure_no = 0
                output.append(f"# 第{chinese_chapter(chapter)}章 {strip_inline(m.group(1), refs)}")
                output.append("")
                continue
            m = re.match(r"\\section\*\{([^}]+)\}", stripped)
            if m:
                flush_para()
                output.append(f"# {strip_inline(m.group(1), refs)}")
                output.append("")
                continue
            m = re.match(r"\\subsection\{([^}]+)\}", stripped)
            if m:
                flush_para()
                section += 1
                subsection = 0
                output.append(f"## {chapter}.{section} {strip_inline(m.group(1), refs)}")
                output.append("")
                continue
            m = re.match(r"\\subsubsection\{([^}]+)\}", stripped)
            if m:
                flush_para()
                subsection += 1
                output.append(f"### {chapter}.{section}.{subsection} {strip_inline(m.group(1), refs)}")
                output.append("")
                continue
            if stripped.startswith(r"\begin{") or stripped.startswith(r"\end{"):
                continue
            para.append(stripped)

        flush_para()
        block = match.group(0)
        if block.startswith(r"\begin{table}"):
            table_no += 1
            output.append(convert_table(block, f"{chapter}-{table_no}" if chapter else str(table_no), refs))
            output.append("")
        elif block.startswith(r"\begin{figure}"):
            figure_no += 1
            output.append(convert_figure(block, f"{chapter}-{figure_no}" if chapter else str(figure_no), refs))
            output.append("")
        else:
            figure_no += 1
            output.append(convert_resultimage(block, f"{chapter}-{figure_no}" if chapter else str(figure_no), refs))
            output.append("")
        pos = match.end()

    tail = text[pos:]
    for line in tail.splitlines():
        stripped = line.strip()
        if not stripped:
            flush_para()
            continue
        if stripped.startswith("%"):
            continue
        if stripped.startswith(r"\clearpage") or stripped.startswith(r"\phantomsection") or stripped.startswith(r"\addcontentsline"):
            continue
        if stripped.startswith(r"\begingroup") or stripped.startswith(r"\endgroup") or stripped.startswith(r"\sloppy"):
            continue
        if stripped.startswith(r"\setlength") or stripped.startswith(r"\hangindent") or stripped.startswith(r"\hangafter") or stripped == r"\wuhao":
            continue
        m = re.match(r"\\section\*\{([^}]+)\}", stripped)
        if m:
            flush_para()
            output.append(f"# {strip_inline(m.group(1), refs)}")
            output.append("")
            continue
        para.append(stripped)
    flush_para()
    return "\n".join(output).strip() + "\n"


def qn(tag: str) -> str:
    return W + tag


def set_child(parent, tag: str):
    child = parent.find(qn(tag))
    if child is None:
        child = etree.SubElement(parent, qn(tag))
    return child


def make_page_field_run():
    field = etree.Element(qn("fldSimple"))
    field.set(qn("instr"), r" PAGE \* MERGEFORMAT ")
    field.append(make_run("1", "18", None, "宋体"))
    return field


def make_footer_xml():
    footer = etree.Element(qn("ftr"), nsmap={"w": NS["w"], "r": NS["r"]})
    p = etree.SubElement(footer, qn("p"))
    ppr = etree.SubElement(p, qn("pPr"))
    jc = etree.SubElement(ppr, qn("jc"))
    jc.set(qn("val"), "center")
    p.append(make_run("- ", "18", None, "宋体"))
    p.append(make_page_field_run())
    p.append(make_run(" -", "18", None, "宋体"))
    return footer


def make_run(text: str, size: str = "24", bold=None, east_asia: str = "宋体"):
    run = etree.Element(qn("r"))
    set_run_font(run, size, bold, east_asia=east_asia)
    t = etree.SubElement(run, qn("t"))
    if text.startswith(" ") or text.endswith(" "):
        t.set(XML_SPACE, "preserve")
    t.text = text
    return run


def make_paragraph(runs, style_id: str, jc=None):
    p = etree.Element(qn("p"))
    set_paragraph_style(p, style_id)
    ppr = p.find(qn("pPr"))
    if jc:
        align = set_child(ppr, "jc")
        align.set(qn("val"), jc)
    for text, size, bold, east_asia in runs:
        p.append(make_run(text, size, bold, east_asia))
    return p


def make_page_break():
    p = etree.Element(qn("p"))
    r = etree.SubElement(p, qn("r"))
    br = etree.SubElement(r, qn("br"))
    br.set(qn("type"), "page")
    return p


def set_run_font(run, size: str, bold=None, east_asia: str = "宋体"):
    rpr = run.find(qn("rPr"))
    if rpr is None:
        rpr = etree.Element(qn("rPr"))
        run.insert(0, rpr)
    fonts = set_child(rpr, "rFonts")
    fonts.set(qn("ascii"), "Times New Roman")
    fonts.set(qn("hAnsi"), "Times New Roman")
    fonts.set(qn("eastAsia"), east_asia)
    fonts.set(qn("cs"), "Times New Roman")
    sz = set_child(rpr, "sz")
    sz.set(qn("val"), size)
    szcs = set_child(rpr, "szCs")
    szcs.set(qn("val"), size)
    if bold is not None:
        b = rpr.find(qn("b"))
        if bold and b is None:
            etree.SubElement(rpr, qn("b"))
        if not bold and b is not None:
            rpr.remove(b)


def paragraph_text(p) -> str:
    return "".join(t.text or "" for t in p.xpath(".//w:t", namespaces=NS))


def set_paragraph_style(p, style_id: str):
    ppr = p.find(qn("pPr"))
    if ppr is None:
        ppr = etree.Element(qn("pPr"))
        p.insert(0, ppr)
    pstyle = ppr.find(qn("pStyle"))
    if pstyle is None:
        pstyle = etree.Element(qn("pStyle"))
        ppr.insert(0, pstyle)
    pstyle.set(qn("val"), style_id)


def clear_indent_and_spacing(p):
    ppr = p.find(qn("pPr"))
    if ppr is None:
        ppr = etree.Element(qn("pPr"))
        p.insert(0, ppr)
    ind = set_child(ppr, "ind")
    ind.set(qn("firstLine"), "0")
    ind.set(qn("firstLineChars"), "0")
    spacing = set_child(ppr, "spacing")
    spacing.set(qn("before"), "0")
    spacing.set(qn("after"), "0")
    spacing.set(qn("line"), "240")
    spacing.set(qn("lineRule"), "auto")


def paragraph_has_page_break(p) -> bool:
    return bool(p.xpath(".//w:br[@w:type='page']", namespaces=NS))


def previous_significant_sibling(node):
    prev = node.getprevious()
    while prev is not None and prev.tag in {qn("bookmarkStart"), qn("bookmarkEnd")}:
        prev = prev.getprevious()
    return prev


def insert_abstract_and_breaks(root, title: str, abstract_paragraphs: list[str], keywords: str):
    body = root.find(qn("body"))
    if body is None:
        return

    if not any(paragraph_text(p).strip() in {"摘要", "摘要："} for p in body.xpath("./w:p", namespaces=NS)):
        abstract_nodes = [make_paragraph([(title, "44", True, "楷体")], "AbstractTitle", "center")]
        abstract_nodes.append(make_paragraph([("摘要：", "32", True, "楷体")], "Abstract"))
        for idx, paragraph in enumerate(abstract_paragraphs):
            abstract_nodes.append(make_paragraph([(paragraph, "24", None, "宋体")], "Abstract"))
        if keywords:
            abstract_nodes.append(
                make_paragraph(
                    [("关键词：", "24", True, "宋体"), (keywords, "24", None, "宋体")],
                    "Abstract",
                )
            )
        abstract_nodes.append(make_page_break())
        body[:0] = abstract_nodes

    for index, child in enumerate(list(body)):
        if child.tag == qn("sdt"):
            next_child = body[index + 1] if index + 1 < len(body) else None
            if next_child is None or next_child.tag != qn("p") or not paragraph_has_page_break(next_child):
                body.insert(index + 1, make_page_break())
            break


def replace_toc(root):
    body = root.find(qn("body"))
    if body is None:
        return
    lines = read_toc_lines()
    toc_nodes = build_static_toc(lines)
    for index, child in enumerate(list(body)):
        if child.tag == qn("sdt"):
            body.remove(child)
            for offset, node in enumerate(toc_nodes):
                body.insert(index + offset, node)
            return


def normalize_heading_page_breaks(root):
    for p in root.xpath(".//w:p", namespaces=NS):
        text = paragraph_text(p).strip()
        style = p.find("./w:pPr/w:pStyle", namespaces=NS)
        if style is None or style.get(qn("val")) != "Heading1":
            continue
        if text == "摘要":
            continue
        ppr = p.find(qn("pPr"))
        if ppr is None:
            ppr = etree.Element(qn("pPr"))
            p.insert(0, ppr)
        existing = ppr.find(qn("pageBreakBefore"))
        prev = previous_significant_sibling(p)
        prev_is_break = (
            prev is not None
            and prev.tag == qn("p")
            and paragraph_has_page_break(prev)
        )
        if prev_is_break:
            if existing is not None:
                ppr.remove(existing)
            continue
        if existing is None:
            pbr = etree.Element(qn("pageBreakBefore"))
            ppr.insert(0, pbr)


def update_doc_styles(styles_path: Path):
    tree = etree.parse(str(styles_path))
    root = tree.getroot()

    def style(style_id: str):
        return root.find(f".//w:style[@w:styleId='{style_id}']", namespaces=NS)

    toc_settings = {
        "TOC1": ("0", "黑体"),
        "TOC2": ("560", "宋体"),
        "TOC3": ("1120", "楷体"),
    }
    for style_id, (left, east_asia) in toc_settings.items():
        st = style(style_id)
        if st is None:
            continue
        ppr = set_child(st, "pPr")
        tabs = set_child(ppr, "tabs")
        for old in list(tabs):
            tabs.remove(old)
        tab = etree.SubElement(tabs, qn("tab"))
        tab.set(qn("val"), "right")
        tab.set(qn("leader"), "dot")
        tab.set(qn("pos"), str(CONTENT_WIDTH))
        spacing = set_child(ppr, "spacing")
        spacing.set(qn("before"), "0")
        spacing.set(qn("after"), "0")
        ind = set_child(ppr, "ind")
        ind.set(qn("left"), left)
        ind.set(qn("firstLine"), "0")
        rpr = set_child(st, "rPr")
        fonts = set_child(rpr, "rFonts")
        fonts.set(qn("ascii"), "Times New Roman")
        fonts.set(qn("hAnsi"), "Times New Roman")
        fonts.set(qn("eastAsia"), east_asia)
        size = set_child(rpr, "sz")
        size.set(qn("val"), "28")
        size_cs = set_child(rpr, "szCs")
        size_cs.set(qn("val"), "28")

    toc_heading = style("TOCHeading")
    if toc_heading is not None:
        ppr = set_child(toc_heading, "pPr")
        jc = set_child(ppr, "jc")
        jc.set(qn("val"), "center")
        rpr = set_child(toc_heading, "rPr")
        fonts = set_child(rpr, "rFonts")
        fonts.set(qn("ascii"), "Times New Roman")
        fonts.set(qn("hAnsi"), "Times New Roman")
        fonts.set(qn("eastAsia"), "黑体")
        size = set_child(rpr, "sz")
        size.set(qn("val"), "30")
        size_cs = set_child(rpr, "szCs")
        size_cs.set(qn("val"), "30")

    tree.write(str(styles_path), encoding="UTF-8", xml_declaration=True, standalone=True)


def set_page_layout(root):
    sect_pr = root.find(".//w:sectPr", namespaces=NS)
    if sect_pr is None:
        body = root.find(qn("body"))
        if body is None:
            return
        sect_pr = etree.SubElement(body, qn("sectPr"))
    pg_sz = set_child(sect_pr, "pgSz")
    pg_sz.set(qn("w"), str(PAGE_WIDTH))
    pg_sz.set(qn("h"), str(PAGE_HEIGHT))
    pg_mar = set_child(sect_pr, "pgMar")
    pg_mar.set(qn("left"), str(MARGIN_LEFT))
    pg_mar.set(qn("right"), str(MARGIN_RIGHT))
    pg_mar.set(qn("top"), str(MARGIN_TOP))
    pg_mar.set(qn("bottom"), str(MARGIN_BOTTOM))
    pg_mar.set(qn("header"), "720")
    pg_mar.set(qn("footer"), "720")
    pg_mar.set(qn("gutter"), "0")


def clone_section_without_page_numbers(sect_pr):
    new = etree.fromstring(etree.tostring(sect_pr))
    for ref in new.findall(qn("footerReference")):
        new.remove(ref)
    pg_num = new.find(qn("pgNumType"))
    if pg_num is not None:
        new.remove(pg_num)
    return new


def ensure_body_page_numbering(root):
    body = root.find(qn("body"))
    if body is None:
        return
    sect_pr = body.find(qn("sectPr"))
    if sect_pr is None:
        sect_pr = etree.SubElement(body, qn("sectPr"))

    footer_ref = sect_pr.find(qn("footerReference"))
    if footer_ref is None:
        footer_ref = etree.Element(qn("footerReference"))
        sect_pr.insert(0, footer_ref)
    footer_ref.set(qn("type"), "default")
    footer_ref.set(R + "id", "rIdDocxPageFooter")

    pg_num = set_child(sect_pr, "pgNumType")
    pg_num.set(qn("start"), "1")

    heading_nodes = [
        p for p in body.xpath("./w:p", namespaces=NS)
        if p.find("./w:pPr/w:pStyle[@w:val='Heading1']", namespaces=NS) is not None
        and paragraph_text(p).strip().startswith("第一章")
    ]
    if not heading_nodes:
        return
    first_heading = heading_nodes[0]

    prev = previous_significant_sibling(first_heading)
    while prev is not None and prev.tag != qn("p"):
        prev = previous_significant_sibling(prev)
    if prev is None:
        return

    prev_ppr = prev.find(qn("pPr"))
    if prev_ppr is None:
        prev_ppr = etree.Element(qn("pPr"))
        prev.insert(0, prev_ppr)
    if prev_ppr.find(qn("sectPr")) is None:
        prev_ppr.append(clone_section_without_page_numbers(sect_pr))


def table_widths(column_count: int) -> list[int]:
    if column_count <= 1:
        return [CONTENT_WIDTH]
    if column_count == 2:
        return [2300, CONTENT_WIDTH - 2300]
    if column_count == 3:
        return [2100, CONTENT_WIDTH - 2100 - 1600, 1600]
    base = CONTENT_WIDTH // column_count
    widths = [base] * column_count
    widths[-1] += CONTENT_WIDTH - sum(widths)
    return widths


def normalize_tables(root):
    for tbl in root.xpath(".//w:tbl", namespaces=NS):
        rows = tbl.xpath("./w:tr", namespaces=NS)
        column_count = max((len(row.xpath("./w:tc", namespaces=NS)) for row in rows), default=1)
        widths = table_widths(column_count)

        tblpr = tbl.find(qn("tblPr"))
        if tblpr is None:
            tblpr = etree.Element(qn("tblPr"))
            tbl.insert(0, tblpr)
        tblw = set_child(tblpr, "tblW")
        tblw.set(qn("type"), "dxa")
        tblw.set(qn("w"), str(CONTENT_WIDTH))
        jc = set_child(tblpr, "jc")
        jc.set(qn("val"), "center")
        layout = set_child(tblpr, "tblLayout")
        layout.set(qn("type"), "fixed")
        cell_mar = set_child(tblpr, "tblCellMar")
        for side, width in {"top": "80", "bottom": "80", "left": "120", "right": "120"}.items():
            item = set_child(cell_mar, side)
            item.set(qn("w"), width)
            item.set(qn("type"), "dxa")

        grid = tbl.find(qn("tblGrid"))
        if grid is None:
            grid = etree.Element(qn("tblGrid"))
            tbl.insert(1, grid)
        for old in list(grid):
            grid.remove(old)
        for width in widths:
            col = etree.SubElement(grid, qn("gridCol"))
            col.set(qn("w"), str(width))

        for row in rows:
            trpr = row.find(qn("trPr"))
            if trpr is None:
                trpr = etree.Element(qn("trPr"))
                row.insert(0, trpr)
            if trpr.find(qn("cantSplit")) is None:
                etree.SubElement(trpr, qn("cantSplit"))

        borders = tblpr.find(qn("tblBorders"))
        if borders is None:
            borders = etree.SubElement(tblpr, qn("tblBorders"))
        for side in ["top", "left", "bottom", "right", "insideH", "insideV"]:
            el = borders.find(qn(side))
            if el is None:
                el = etree.SubElement(borders, qn(side))
            el.set(qn("val"), "single")
            el.set(qn("sz"), "4")
            el.set(qn("space"), "0")
            el.set(qn("color"), "808080")

        for row_index, row in enumerate(rows):
            cells = row.xpath("./w:tc", namespaces=NS)
            for col_index, cell in enumerate(cells):
                tcpr = cell.find(qn("tcPr"))
                if tcpr is None:
                    tcpr = etree.Element(qn("tcPr"))
                    cell.insert(0, tcpr)
                tcw = set_child(tcpr, "tcW")
                tcw.set(qn("type"), "dxa")
                tcw.set(qn("w"), str(widths[min(col_index, len(widths) - 1)]))
                if row_index == 0:
                    shd = set_child(tcpr, "shd")
                    shd.set(qn("val"), "clear")
                    shd.set(qn("fill"), "EBF0F6")

        first_row = tbl.find(qn("tr"))
        if first_row is not None:
            for r in first_row.xpath(".//w:r", namespaces=NS):
                set_run_font(r, "21", True)

        next_node = tbl.getnext()
        while next_node is not None and next_node.tag in {qn("bookmarkStart"), qn("bookmarkEnd")}:
            next_node = next_node.getnext()
        if next_node is not None and next_node.tag == qn("p"):
            ppr = next_node.find(qn("pPr"))
            if ppr is None:
                ppr = etree.Element(qn("pPr"))
                next_node.insert(0, ppr)
            spacing = set_child(ppr, "spacing")
            spacing.set(qn("before"), "120")
            spacing.set(qn("after"), "0")


def update_settings(settings_path: Path):
    tree = etree.parse(str(settings_path))
    root = tree.getroot()
    update = root.find(qn("updateFields"))
    if update is None:
        update = etree.SubElement(root, qn("updateFields"))
    update.set(qn("val"), "true")
    tree.write(str(settings_path), encoding="UTF-8", xml_declaration=True, standalone=True)


def ensure_footer_part(tmp: Path):
    footer_path = tmp / "word" / "footer1.xml"
    footer_tree = etree.ElementTree(make_footer_xml())
    footer_tree.write(str(footer_path), encoding="UTF-8", xml_declaration=True, standalone=True)

    rels_path = tmp / "word" / "_rels" / "document.xml.rels"
    rels_tree = etree.parse(str(rels_path))
    rels_root = rels_tree.getroot()
    rel_tag = f"{{{PKG_REL_NS}}}Relationship"
    existing = rels_root.find(f"{rel_tag}[@Id='rIdDocxPageFooter']")
    if existing is None:
        existing = etree.SubElement(rels_root, rel_tag)
    existing.set("Id", "rIdDocxPageFooter")
    existing.set("Type", "http://schemas.openxmlformats.org/officeDocument/2006/relationships/footer")
    existing.set("Target", "footer1.xml")
    rels_tree.write(str(rels_path), encoding="UTF-8", xml_declaration=True, standalone=True)

    content_types_path = tmp / "[Content_Types].xml"
    ct_tree = etree.parse(str(content_types_path))
    ct_root = ct_tree.getroot()
    ns = ct_root.nsmap.get(None)
    override_tag = f"{{{ns}}}Override" if ns else "Override"
    part_name = "/word/footer1.xml"
    if ct_root.find(f"{override_tag}[@PartName='{part_name}']") is None:
        override = etree.SubElement(ct_root, override_tag)
        override.set("PartName", part_name)
        override.set("ContentType", "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml")
    ct_tree.write(str(content_types_path), encoding="UTF-8", xml_declaration=True, standalone=True)


def postprocess_docx(path: Path):
    with tempfile.TemporaryDirectory() as td:
        tmp = Path(td)
        with zipfile.ZipFile(path) as zf:
            zf.extractall(tmp)

        doc_path = tmp / "word" / "document.xml"
        tree = etree.parse(str(doc_path))
        root = tree.getroot()
        replace_toc(root)
        normalize_heading_page_breaks(root)
        set_page_layout(root)
        ensure_body_page_numbering(root)

        for p in root.xpath(".//w:p", namespaces=NS):
            text = paragraph_text(p).strip()
            in_table = bool(p.xpath("ancestor::w:tbl", namespaces=NS))
            has_drawing = bool(p.xpath(".//w:drawing", namespaces=NS))
            if has_drawing:
                set_paragraph_style(p, "CaptionedFigure")
                ppr = p.find(qn("pPr"))
                if ppr is not None:
                    jc = set_child(ppr, "jc")
                    jc.set(qn("val"), "center")
                    ind = set_child(ppr, "ind")
                    ind.set(qn("firstLine"), "0")
                    ind.set(qn("firstLineChars"), "0")
                    spacing = set_child(ppr, "spacing")
                    spacing.set(qn("before"), "60")
                    spacing.set(qn("after"), "60")
            elif re.match(r"^(表|图) \d+(?:-\d+)?\u3000", text):
                set_paragraph_style(p, "TableCaption" if text.startswith("表") else "ImageCaption")
                ppr = p.find(qn("pPr"))
                if ppr is not None:
                    keep_next = ppr.find(qn("keepNext"))
                    if keep_next is None:
                        etree.SubElement(ppr, qn("keepNext"))
                    jc = set_child(ppr, "jc")
                    jc.set(qn("val"), "center")
                    ind = set_child(ppr, "ind")
                    ind.set(qn("firstLine"), "0")
                    ind.set(qn("firstLineChars"), "0")
                for r in p.findall(qn("r")):
                    set_run_font(r, "21", True)
            elif re.match(r"^\[\d+\]", text):
                clear_indent_and_spacing(p)
                for r in p.findall(qn("r")):
                    set_run_font(r, "21", False)
            elif in_table:
                clear_indent_and_spacing(p)
                for r in p.findall(qn("r")):
                    set_run_font(r, "21", None)

        normalize_tables(root)

        tree.write(str(doc_path), encoding="UTF-8", xml_declaration=True, standalone=True)
        ensure_footer_part(tmp)
        update_doc_styles(tmp / "word" / "styles.xml")
        update_settings(tmp / "word" / "settings.xml")

        new_path = path.with_suffix(".tmp.docx")
        with zipfile.ZipFile(new_path, "w", zipfile.ZIP_DEFLATED) as zf:
            for file in tmp.rglob("*"):
                if file.is_file():
                    zf.write(file, file.relative_to(tmp).as_posix())
        new_path.replace(path)


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("-o", "--output", default=str(ROOT / "dist" / "学院生活平台计算机综合实训报告-正文.docx"))
    parser.add_argument("--reference-doc", default=str(ROOT / "reference.docx"))
    args = parser.parse_args()

    build = ROOT / "build"
    build.mkdir(exist_ok=True)
    out = Path(args.output)
    out.parent.mkdir(parents=True, exist_ok=True)

    text = read_expanded_body()
    md = convert_tex_to_markdown(text)
    md_path = build / "docx_body.md"
    raw_docx = build / "docx_raw.docx"
    md_path.write_text(md, encoding="utf-8")

    subprocess.run(
        [
            "pandoc",
            str(md_path),
            "-f",
            "markdown+pipe_tables+implicit_figures",
            "-t",
            "docx",
            "--toc",
            "--toc-depth=3",
            "--metadata",
            "toc-title=目录",
            f"--reference-doc={args.reference_doc}",
            "--resource-path=.:assets:assets/figures:assets/figures/er",
            "-o",
            str(raw_docx),
        ],
        cwd=ROOT,
        check=True,
    )
    shutil.copyfile(raw_docx, out)
    postprocess_docx(out)


if __name__ == "__main__":
    main()
