#!/usr/bin/env python3
"""把工作副本上的公式缓存值与 AIGC 标识写回交付件 预算.xlsx。

为什么不用插件自带的 aigc_label.py / recalc.py 直接写交付件：
那两个脚本都用「先写临时文件 → os.replace 原子替换」的方式落盘，而本机的
文件策略拒绝了这种两路径操作（Brokered two-path operation is not allowed），
随之而来的临时文件清理也会被拒绝。本脚本因此：

  1. 只做**单路径写入**：读工作副本的内容，直接以覆盖方式写进交付件，
     不创建临时文件、不 os.replace、不 os.unlink，交付件路径始终存在；
  2. 保留原件副本（outputs/.预算.ref/预算-原件备份-未标识.xlsx）与工作副本，
     便于回溯核对；
  3. 标识内容与插件 aigc_label.py 的规范一致（Label / ContentProducer /
     ProduceID / ContentPropagator / PropagateID），预留码留空。

用法：python3 outputs/scripts/stamp_label.py
依赖：Python 3.11+ 标准库（zipfile / json / uuid / xml），无需第三方包。
"""
from __future__ import annotations

import json
import uuid
import zipfile
from pathlib import Path
from xml.etree import ElementTree as ET

ROOT = Path(__file__).resolve().parents[2]
OUT = ROOT / "outputs"
REF = OUT / ".预算.ref"
TARGET = OUT / "预算.xlsx"
WORKING = REF / "预算-工作副本.xlsx"
BACKUP = REF / "预算-原件备份-未标识.xlsx"

CUSTOM_NS = "http://schemas.openxmlformats.org/officeDocument/2006/custom-properties"
VT_NS = "http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes"
CT_NS = "http://schemas.openxmlformats.org/package/2006/content-types"
RELS_NS = "http://schemas.openxmlformats.org/package/2006/relationships"
CUSTOM_PART = "docProps/custom.xml"
CUSTOM_CT = "application/vnd.openxmlformats-officedocument.custom-properties+xml"
CUSTOM_REL_TYPE = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties"
FMTID = "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}"
PROPERTY_NAME = "AIGC"
LOCAL_CONTENT_PRODUCER = "00119111010856365494821B355"


def build_payload(produce_id: str) -> str:
    fields = [
        ("Label", "1"),
        ("ContentProducer", LOCAL_CONTENT_PRODUCER),
        ("ProduceID", produce_id),
        ("ContentPropagator", LOCAL_CONTENT_PRODUCER),
        ("PropagateID", produce_id),
    ]
    return json.dumps(dict(fields), ensure_ascii=False, separators=(",", ":"))


def next_pid(root: ET.Element) -> str:
    pids = [int(p.get("pid", 1)) for p in root.findall(f"{{{CUSTOM_NS}}}property")]
    return str(max(pids + [1]) + 1)


def custom_xml_with_label(existing: bytes | None, payload: str) -> bytes:
    ET.register_namespace("", CUSTOM_NS)
    ET.register_namespace("vt", VT_NS)
    if existing:
        root = ET.fromstring(existing)
        for prop in root.findall(f"{{{CUSTOM_NS}}}property"):
            if prop.get("name") == PROPERTY_NAME:
                root.remove(prop)
    else:
        root = ET.Element(f"{{{CUSTOM_NS}}}Properties")
    prop = ET.SubElement(root, f"{{{CUSTOM_NS}}}property",
                         {"fmtid": FMTID, "pid": next_pid(root), "name": PROPERTY_NAME})
    ET.SubElement(prop, f"{{{VT_NS}}}lpwstr").text = payload
    return b'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n' + ET.tostring(root, encoding="utf-8")


def content_types_with_custom(data: bytes) -> bytes:
    ET.register_namespace("", CT_NS)
    root = ET.fromstring(data)
    for ov in root.findall(f"{{{CT_NS}}}Override"):
        if ov.get("PartName") == f"/{CUSTOM_PART}":
            return ET.tostring(root, encoding="utf-8", xml_declaration=True)
    ET.SubElement(root, f"{{{CT_NS}}}Override",
                  {"PartName": f"/{CUSTOM_PART}", "ContentType": CUSTOM_CT})
    return ET.tostring(root, encoding="utf-8", xml_declaration=True)


def rels_with_custom(data: bytes) -> bytes:
    ET.register_namespace("", RELS_NS)
    root = ET.fromstring(data)
    ids = set()
    for rel in root.findall(f"{{{RELS_NS}}}Relationship"):
        if rel.get("Target") in (CUSTOM_PART, f"/{CUSTOM_PART}"):
            return ET.tostring(root, encoding="utf-8", xml_declaration=True)
        ids.add(rel.get("Id"))
    n = 1
    while f"rId{n}" in ids:
        n += 1
    ET.SubElement(root, f"{{{RELS_NS}}}Relationship",
                  {"Id": f"rId{n}", "Type": CUSTOM_REL_TYPE, "Target": CUSTOM_PART})
    return ET.tostring(root, encoding="utf-8", xml_declaration=True)


def read_label(path: Path) -> str | None:
    try:
        with zipfile.ZipFile(path) as zf:
            if CUSTOM_PART not in zf.namelist():
                return None
            root = ET.fromstring(zf.read(CUSTOM_PART))
    except (zipfile.BadZipFile, ET.ParseError):
        return None
    for prop in root.findall(f"{{{CUSTOM_NS}}}property"):
        if prop.get("name") == PROPERTY_NAME:
            node = prop.find(f"{{{VT_NS}}}lpwstr")
            return node.text if node is not None else None
    return None


def main() -> None:
    if not WORKING.is_file():
        raise SystemExit(f"缺少工作副本：{WORKING}")
    if not BACKUP.is_file():
        raise SystemExit(f"缺少原件备份：{BACKUP}")

    with zipfile.ZipFile(WORKING) as zf:
        names = zf.namelist()
        contents = {n: zf.read(n) for n in names}

    produce_id = uuid.uuid4().hex
    payload = build_payload(produce_id)
    contents[CUSTOM_PART] = custom_xml_with_label(contents.get(CUSTOM_PART), payload)
    if "[Content_Types].xml" in contents:
        contents["[Content_Types].xml"] = content_types_with_custom(contents["[Content_Types].xml"])
    if "_rels/.rels" in contents:
        contents["_rels/.rels"] = rels_with_custom(contents["_rels/.rels"])

    order = names + [n for n in contents if n not in names]

    # 单路径写入：直接覆盖目标文件，不创建/替换/删除任何其它路径。
    with zipfile.ZipFile(TARGET, "w", zipfile.ZIP_DEFLATED) as zout:
        for name in order:
            zout.writestr(name, contents[name])

    written = read_label(TARGET)
    if written != payload:
        raise SystemExit("标识回读不一致，写入失败")
    print(json.dumps({"status": "labeled", "target": str(TARGET), "label": written,
                      "parts": len(order)}, ensure_ascii=False))


if __name__ == "__main__":
    main()
