"""Create editable, synthetic POC Word artifacts through the managed Office runtime."""
import argparse
import json
from pathlib import Path
from zipfile import ZipFile
from xml.etree import ElementTree as ET

from docx import Document
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
from docx.shared import Mm, Pt, RGBColor


def font(run, name, size, color=None):
    run.font.name = name
    run.font.size = Pt(size)
    fonts = run._element.get_or_add_rPr().get_or_add_rFonts()
    fonts.set(qn("w:eastAsia"), name)
    if color:
        run.font.color.rgb = RGBColor.from_string(color)


def bookmark(paragraph, name, value, number):
    start = OxmlElement("w:bookmarkStart")
    start.set(qn("w:id"), str(number))
    start.set(qn("w:name"), name)
    paragraph._p.append(start)
    run = paragraph.add_run(value)
    end = OxmlElement("w:bookmarkEnd")
    end.set(qn("w:id"), str(number))
    paragraph._p.append(end)
    return run


def create(path, sample):
    doc = Document()
    doc.core_properties.title = "智能公文POC公文红模板"
    doc.core_properties.subject = "合成POC可编辑模板，不代表正式机关或批准文件"
    doc.core_properties.author = "E10智能公文POC"
    section = doc.sections[0]
    section.page_width, section.page_height = Mm(210), Mm(297)
    section.top_margin, section.bottom_margin = Mm(30), Mm(28)
    section.left_margin, section.right_margin = Mm(27), Mm(25)
    normal = doc.styles["Normal"]
    normal.font.name = "Songti SC"
    normal.font.size = Pt(16)
    normal.paragraph_format.line_spacing = Pt(28)
    normal.paragraph_format.space_after = Pt(0)

    p = doc.add_paragraph()
    p.alignment = WD_ALIGN_PARAGRAPH.CENTER
    p.paragraph_format.space_after = Pt(12)
    font(bookmark(p, "issuer_name", "智能公文POC测试单位", 1), "Songti SC", 27, "B51F2B")
    border = OxmlElement("w:pBdr")
    bottom = OxmlElement("w:bottom")
    for key, value in {"val": "single", "sz": "16", "space": "8", "color": "B51F2B"}.items():
        bottom.set(qn("w:" + key), value)
    border.append(bottom)
    p._p.get_or_add_pPr().append(border)

    p = doc.add_paragraph()
    p.alignment = WD_ALIGN_PARAGRAPH.CENTER
    p.paragraph_format.space_after = Pt(12)
    font(bookmark(p, "document_number", "POC〔2026〕1号" if sample else "{{公文编号}}", 2), "Songti SC", 12)

    p = doc.add_paragraph()
    p.alignment = WD_ALIGN_PARAGRAPH.CENTER
    p.paragraph_format.space_after = Pt(12)
    title = "关于智能公文POC项目实施的请示" if sample else "{{公文标题}}"
    font(bookmark(p, "document_title", title, 3), "Songti SC", 19)

    p = doc.add_paragraph()
    font(bookmark(p, "recipient_name", "POC审核人员：" if sample else "{{主送单位}}：", 4), "Songti SC", 16)

    p = doc.add_paragraph()
    p.paragraph_format.first_line_indent = Pt(32)
    body = ("本次申请实施智能公文POC项目，申请金额为95万元（含税）。"
            "合成前序批准金额为100万元（含税），申请金额未超出该合成批准金额。"
            "本文件仅用于配置与演示验证，审核结论以原生表单中人工确认的结果为准。"
            if sample else "{{公文正文}}")
    # E10 native odoc reserves this exact name for the Office document body.
    # A TextArea dataKey is not a substitute for the native body bookmark.
    font(bookmark(p, "Content", body, 5), "Songti SC", 16)

    p = doc.add_paragraph("妥否，请批示。" if sample else "{{结束语}}")
    p.paragraph_format.first_line_indent = Pt(32)
    p.paragraph_format.space_after = Pt(12)

    p = doc.add_paragraph()
    p.alignment = WD_ALIGN_PARAGRAPH.RIGHT
    font(bookmark(p, "draft_department", "POC起草部门" if sample else "{{起草部门}}", 6), "Songti SC", 16)
    p = doc.add_paragraph()
    p.alignment = WD_ALIGN_PARAGRAPH.RIGHT
    font(bookmark(p, "document_date", "2026年10月12日" if sample else "{{成文日期}}", 7), "Songti SC", 16)

    footer = section.footer.paragraphs[0]
    footer.alignment = WD_ALIGN_PARAGRAPH.CENTER
    font(footer.add_run("合成POC示例 · "), "Songti SC", 9, "666666")
    field = OxmlElement("w:fldSimple")
    field.set(qn("w:instr"), "PAGE")
    footer._p.append(field)
    doc.save(path)


def verify(path, sample):
    ns = {"w": "http://schemas.openxmlformats.org/wordprocessingml/2006/main"}
    with ZipFile(path) as archive:
        root = ET.fromstring(archive.read("word/document.xml"))
        text = "".join(root.itertext())
        names = [x.attrib[qn("w:name")] for x in root.findall(".//w:bookmarkStart", ns)]
        assert len(names) == len(set(names)) == 7
        assert "Content" in names and "document_title" in names
        assert "document_body" not in names
        assert root.find(".//w:pBdr/w:bottom", ns).attrib[qn("w:color")] == "B51F2B"
        assert "智能公文POC测试单位" in text
        assert ("95万元" in text) if sample else ("{{公文正文}}" in text)
        assert not any("vbaProject" in name for name in archive.namelist())
    return {"file": path.name, "bookmarks": len(names), "bodyBookmark": "Content",
            "nativeImportVerified": False, "dynamicMappingVerified": False, "editableText": True,
            "synthetic": True, "redHeader": True, "macroFree": True, "bytes": path.stat().st_size}


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--output", required=True)
    args = parser.parse_args()
    target = Path(args.output)
    target.mkdir(parents=True, exist_ok=True)
    files = [("智能公文-公文红模板.docx", False), ("智能公文-套红合成示例.docx", True)]
    for name, _ in files:
        if (target / name).exists():
            raise ValueError("artifact_exists; inspect existing files instead of overwriting")
    checks = []
    for name, sample in files:
        path = target / name
        create(path, sample)
        checks.append(verify(path, sample))
    print(json.dumps({"status": "created_and_structurally_verified", "files": checks}, ensure_ascii=False))


if __name__ == "__main__":
    main()
