"""共享的最小 OOXML .docx 打包实现。"""

from __future__ import annotations

import io
import re
import zipfile
from xml.etree import ElementTree as ET

_WORDPROCESSING_NS = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
_XML_NS = "http://www.w3.org/XML/1998/namespace"
ET.register_namespace("w", _WORDPROCESSING_NS)


def _word_tag(name: str) -> str:
    return f"{{{_WORDPROCESSING_NS}}}{name}"


def _append_word_paragraph(body: ET.Element, raw_line: str) -> None:
    line = raw_line.rstrip()
    heading = re.match(r"^(#{1,6})\s+(.+)$", line)
    bullet = re.match(r"^\s*[-*]\s+(.+)$", line)
    numbered = re.match(r"^\s*(\d+)[.、)]\s+(.+)$", line)
    quote = re.match(r"^\s*>\s?(.*)$", line)
    is_heading = heading is not None
    if heading:
        text = heading.group(2)
    elif bullet:
        text = f"• {bullet.group(1)}"
    elif numbered:
        text = f"{numbered.group(1)}. {numbered.group(2)}"
    elif quote:
        text = quote.group(1)
    elif line.startswith("|") and line.endswith("|"):
        cells = [cell.strip() for cell in line.strip("|").split("|")]
        if cells and all(re.fullmatch(r":?-{3,}:?", cell) for cell in cells):
            return
        text = "\t".join(cells)
    else:
        text = line

    paragraph = ET.SubElement(body, _word_tag("p"))
    run = ET.SubElement(paragraph, _word_tag("r"))
    if is_heading:
        run_properties = ET.SubElement(run, _word_tag("rPr"))
        ET.SubElement(run_properties, _word_tag("b"))
        size = ET.SubElement(run_properties, _word_tag("sz"))
        # 标题字号随层级递减,24 为下限
        size.set(_word_tag("val"), str(max(24, 36 - 4 * len(heading.group(1)))))
    text_node = ET.SubElement(run, _word_tag("t"))
    text_node.set(f"{{{_XML_NS}}}space", "preserve")
    text_node.text = text.replace("**", "").replace("`", "")


def _word_document_xml(content: str) -> bytes:
    document = ET.Element(_word_tag("document"))
    body = ET.SubElement(document, _word_tag("body"))
    for line in content.splitlines():
        _append_word_paragraph(body, line)
    section = ET.SubElement(body, _word_tag("sectPr"))
    page_size = ET.SubElement(section, _word_tag("pgSz"))
    page_size.set(_word_tag("w"), "11906")
    page_size.set(_word_tag("h"), "16838")
    margins = ET.SubElement(section, _word_tag("pgMar"))
    for name, value in {
        "top": "1440",
        "right": "1440",
        "bottom": "1440",
        "left": "1440",
        "header": "720",
        "footer": "720",
        "gutter": "0",
    }.items():
        margins.set(_word_tag(name), value)
    return ET.tostring(document, encoding="utf-8", xml_declaration=True)


def build_docx_package(content: str) -> tuple[bytes, bytes]:
    """Markdown 纯文本打成最小三件套 .docx,返回 (zip 字节, document.xml 字节)。

    固定三条目:[Content_Types].xml、_rels/.rels、word/document.xml;
    无 styles.xml,样式内联在段落 run 上。document.xml 一并返回供回读比对。
    """
    document_xml = _word_document_xml(content)
    output = io.BytesIO()
    with zipfile.ZipFile(output, "w", zipfile.ZIP_DEFLATED) as archive:
        archive.writestr(
            "[Content_Types].xml",
            """<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
  <Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
  <Default Extension="xml" ContentType="application/xml"/>
  <Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>
</Types>""",
        )
        archive.writestr(
            "_rels/.rels",
            """<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
  <Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>
</Relationships>""",
        )
        archive.writestr("word/document.xml", document_xml)
    return output.getvalue(), document_xml