#!/usr/bin/env python3
"""W07 交付件自检：内容 / 预算 / 时段 / 打包清单 / 标识 / Word 打印适配。

只读校验：除最后写出的 outputs/data/交付核对.json 外，不修改任何成品；
不启动 headless 浏览器或 LibreOffice，不删除任何文件。

依赖：Python 3.11+ 标准库 + openpyxl（读取 xlsx 缓存值）。
"""
from __future__ import annotations

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

from openpyxl import load_workbook

ROOT = Path(__file__).resolve().parents[2]
OUT = ROOT / "outputs"
DATA = json.loads((OUT / "data" / "旅行数据.json").read_text(encoding="utf-8"))
HTML = (OUT / "旅行手册.html").read_text(encoding="utf-8")
RAIN = (OUT / "雨天替代.md").read_text(encoding="utf-8")
STAGE_HTML = (OUT / "_build" / "70e5e81f-3eac-4ec3-8893-22f0f80d8c01" / "stage2" / "formatted-青禾市两天随身旅行手册.html").read_text(encoding="utf-8")
DOCX = OUT / "行程.docx"
XLSX = OUT / "预算.xlsx"

W = "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}"
CUSTOM_NS = "http://schemas.openxmlformats.org/officeDocument/2006/custom-properties"

# 合并规则期望值：同名每人取最大值 → 乘 2 人；水杯/充电线跨场景不累加。
EXPECTED_PACKING = {
    "水杯": ("1 个", "2 个"),
    "充电线": ("1 条", "2 条"),
    "帽子": ("1 顶", "2 顶"),
    "折叠伞": ("1 把", "2 把"),
    "防水袋": ("2 个", "4 个"),
}

checks: list[dict] = []
failures: list[str] = []


def check(name: str, ok: bool, detail: str) -> None:
    checks.append({"name": name, "passed": bool(ok), "detail": detail})
    if not ok:
        failures.append(f"{name}：{detail}")


def minutes(hhmm: str) -> int:
    h, m = hhmm.split(":")
    return int(h) * 60 + int(m)


# ---------- 1. 文件存在 ----------
check("四项成品存在且非空",
      all((OUT / n).is_file() and (OUT / n).stat().st_size > 0
          for n in ["行程.docx", "预算.xlsx", "雨天替代.md", "旅行手册.html"]),
      "行程.docx、预算.xlsx、雨天替代.md、旅行手册.html")

# ---------- 2. 行程结构与时段 ----------
days = DATA["itinerary"]
total_segments = sum(len(d["segments"]) for d in days)
check("时间轴段数", len(days) == 3 and total_segments == 31,
      f"第一天 {len(days[0]['segments'])} 段；第二天晴天 {len(days[1]['segments'])} 段；第二天雨天 {len(days[2]['segments'])} 段；共 {total_segments} 段")

for day in days:
    segs = day["segments"]
    contiguous = all(prev["end"] == curr["start"] for prev, curr in zip(segs, segs[1:]))
    check(f"{day['title']} 时段连续", contiguous and segs[0]["start"] == "09:00" and segs[-1]["end"] == "18:00",
          f"09:00 → 18:00 连续覆盖，段间无缝隙")
    transit_ok = all(
        (s["kind"] != "交通")
        or (minutes(s["end"]) - minutes(s["start"]) == 20
            and i + 1 < len(segs) and segs[i + 1]["kind"] == "缓冲"
            and minutes(segs[i + 1]["end"]) - minutes(segs[i + 1]["start"]) == 10)
        for i, s in enumerate(segs))
    check(f"{day['title']} 交通 20 分钟且后接 10 分钟缓冲", transit_ok,
          "每段交通 20 分钟，其后紧跟 10 分钟缓冲")

opening_ok = True
for day in days:
    for s in day["segments"]:
        if not s["location"] or s["kind"] not in {"参观", "游览", "停留"}:
            continue
        loc = DATA["locations"][s["location"]]
        window = loc[f"{day['weekday']}开放"]
        if window == "关闭":
            opening_ok = False
            continue
        op, cl = window.split("-")
        if minutes(s["start"]) < minutes(op) or minutes(s["end"]) > minutes(cl):
            opening_ok = False
        if minutes(s["end"]) - minutes(s["start"]) != loc["停留分钟"]:
            opening_ok = False
check("开放时间与停留时长核对", opening_ok,
      "博物馆排在周二 09:00-17:00；艺术馆 10:00-17:00；老街/公园/书店 09:00-18:00；停留分钟与资料一致")

sunny = next(d for d in days if d["id"] == "day2_sunny")["segments"]
rainy = next(d for d in days if d["id"] == "day2_rain")["segments"]
check("晴雨时间轴一致",
      [(x["start"], x["end"]) for x in sunny] == [(x["start"], x["end"]) for x in rainy],
      "第二天仅把公园替换为室内书店，起止时间、交通与缓冲完全不变")

# ---------- 3. 打包清单合并结果 ----------
merged = {x["item"]: x for x in DATA["packing_list"]}
packing_ok = set(merged) == set(EXPECTED_PACKING)
detail_bits = []
for item, (per, total) in EXPECTED_PACKING.items():
    got = merged.get(item)
    if not got or got["per_person_text"] != per or got["quantity_text"] != total:
        packing_ok = False
    detail_bits.append(f"{item} {got['per_person_text']}→{got['quantity_text']}" if got else f"{item} 缺失")
check("合并打包清单 5 项且数量正确", packing_ok, "；".join(detail_bits))

no_accumulate = (merged.get("水杯", {}).get("per_person") == 1
                  and merged.get("充电线", {}).get("per_person") == 1)
check("水杯/充电线不重复累加", no_accumulate,
      "水杯出现于通用与晴天、充电线出现于通用与雨天，均按每人最大值 1 计算后乘 2，未累加")
check("打包清单场景保留", all(merged[i]["scenario"] for i in EXPECTED_PACKING),
      "；".join(f"{k}：{merged[k]['scenario']}" for k in EXPECTED_PACKING))

# 清单必须在四成品 + 共享 JSON 中都出现
def has_packing(text: str) -> bool:
    return all(item in text for item in EXPECTED_PACKING)

check("HTML 含合并清单", has_packing(HTML) and "2 个" in HTML and "4 个" in HTML,
      "旅行手册.html 列出 5 项及两人合计")
check("雨天替代含合并清单", has_packing(RAIN) and "2 个" in RAIN and "4 个" in RAIN,
      "雨天替代.md 列出 5 项及两人合计")
check("共享 JSON 含合并清单", has_packing(json.dumps(DATA, ensure_ascii=False)),
      "outputs/data/旅行数据.json 的 packing_list 为 5 项合并结果")

docx_text = ""
with zipfile.ZipFile(DOCX) as zf:
    docx_xml = zf.read("word/document.xml").decode("utf-8")
    docx_text = "".join(ET.fromstring(docx_xml).itertext())
check("Word 含合并清单", has_packing(docx_text) and "2 个" in docx_text and "4 个" in docx_text,
      "行程.docx 列出 5 项及两人合计")

# ---------- 4. 预算 ----------
for scenario in ("晴天", "雨天"):
    b = DATA["budgets"][scenario]
    check(f"{scenario}预算复算",
          b["known_total"] == 724 and b["known_per_person"] == 362 and b["remaining"] == 476,
          f"确定总额 {b['known_total']} 元；人均 {b['known_per_person']:.0f} 元；上限 {b['cap']} 元；余量 {b['remaining']} 元")

wb = load_workbook(XLSX, data_only=True, read_only=True)
ws = wb["预算汇总"]
cached = {c: ws[c].value for c in ["B5", "C5", "B6", "C6", "B7", "C7", "B8", "C8", "C9", "C10", "C11", "C12", "B13", "C13"]}
check("预算公式缓存已写入",
      cached["B5"] == 724 and cached["C5"] == 724 and cached["B6"] == 362 and cached["C6"] == 362
      and cached["B8"] == 476 and cached["C8"] == 476 and cached["C12"] == 476
      and cached["B7"] == 1200 and cached["C7"] == 1200,
      json.dumps(cached, ensure_ascii=False))
check("未知消费 X 保持待确认",
      cached["C9"] == "待确认（未计入）" and cached["C10"] == "待确认" and cached["C11"] == "待确认" and cached["C13"] == "待确认",
      f"C9={cached['C9']}；C10={cached['C10']}；C11={cached['C11']}；C13={cached['C13']}")
check("晴天状态判定", cached["B13"] == "未超上限", f"B13={cached['B13']}")

ws_p = wb["待确认与打包"]
xl_packing = {ws_p.cell(r, 1).value: (ws_p.cell(r, 2).value, ws_p.cell(r, 3).value)
               for r in range(4, 9)}
check("工作簿清单页同步",
      set(xl_packing) == set(EXPECTED_PACKING)
      and all(xl_packing[k] == EXPECTED_PACKING[k] for k in EXPECTED_PACKING),
      "；".join(f"{k} {v[0]}→{v[1]}" for k, v in xl_packing.items()))
check("工作簿结构", wb.sheetnames == ["预算汇总", "预算明细", "输入与规则", "结构化行程", "待确认与打包"],
      "、".join(wb.sheetnames))
wb.close()

# 全部公式格的缓存值覆盖率（按 XML 中 <v> 是否存在判定，
# 未知消费项的合法结果是 t="str" + 空 <v>，openpyxl 会读成 None）
with zipfile.ZipFile(XLSX) as zf:
    wb_f = load_workbook(XLSX, data_only=False)
    formula_cells = []
    for sheet in wb_f.sheetnames:
        for row in wb_f[sheet].iter_rows():
            for cell in row:
                if isinstance(cell.value, str) and cell.value.startswith("="):
                    formula_cells.append((sheet, cell.coordinate))
    wb_f.close()

    def sheet_paths(contents):
        rels = ET.fromstring(contents["xl/_rels/workbook.xml.rels"])
        target = {r.get("Id"): r.get("Target") for r in rels}
        wb = ET.fromstring(contents["xl/workbook.xml"])
        out = {}
        for sh in wb.find(f"{{http://schemas.openxmlformats.org/spreadsheetml/2006/main}}sheets"):
            rid = sh.get("{http://schemas.openxmlformats.org/officeDocument/2006/relationships}id")
            t = target.get(rid, "")
            out[sh.get("name")] = "xl/" + t.lstrip("/") if not t.startswith("/") else t.lstrip("/")
        return out

    contents = {n: zf.read(n) for n in zf.namelist()}
    paths = sheet_paths(contents)
    no_value = []
    for sheet, coord in formula_cells:
        xml = ET.fromstring(contents[paths[sheet]])
        found = False
        for c in xml.iter(f"{{http://schemas.openxmlformats.org/spreadsheetml/2006/main}}c"):
            if c.get("r") == coord and c.find(
                    "{http://schemas.openxmlformats.org/spreadsheetml/2006/main}v") is not None:
                found = True
                break
        if not found:
            no_value.append(f"{sheet}!{coord}")
check("全部公式格均有缓存值", len(formula_cells) == 75 and not no_value,
      f"{len(formula_cells)} 个公式格全部带 <v> 缓存值（含未知消费项的空串结果）；"
      "无缓存的格：" + ("、".join(no_value) if no_value else "无"))

# ---------- 5. 生成标识（core properties，不依赖插件私有标识） ----------
wb_props = load_workbook(XLSX, read_only=True)
props = wb_props.properties
core = {"creator": props.creator, "lastModifiedBy": props.lastModifiedBy,
        "title": props.title, "description": props.description}
wb_props.close()
check("预算.xlsx core properties 已写入",
      core["creator"] == "WorkBuddy AI生成"
      and core["lastModifiedBy"] == "WorkBuddy AI生成"
      and bool(core["description"])
      and "WorkBuddy AI生成" in core["description"],
      f"creator={core['creator']}；lastModifiedBy={core['lastModifiedBy']}；"
      f"title={core['title']}；description={core['description']}")
with zipfile.ZipFile(XLSX) as zf:
    xlsx_parts = zf.namelist()
check("预算.xlsx 含 docProps/core.xml", "docProps/core.xml" in xlsx_parts,
      f"工作簿包含 {len(xlsx_parts)} 个包内条目，core properties 可被 Excel / WPS / 预览器读取")

# ---------- 6. Word 打印适配 ----------
with zipfile.ZipFile(DOCX) as zf:
    docx_xml = zf.read("word/document.xml").decode("utf-8")
root = ET.fromstring(docx_xml)
body = root.find(f"{W}body")
sect = body.find(f"{W}sectPr")
pg = sect.find(f"{W}pgSz")
mar = sect.find(f"{W}pgMar")
usable = int(pg.get(f"{W}w")) - int(mar.get(f"{W}left")) - int(mar.get(f"{W}right"))
tables = body.findall(f"{W}tbl")
over = []
widths = []
for i, tb in enumerate(tables):
    grid = tb.find(f"{W}tblGrid")
    cols = [int(c.get(f"{W}w")) for c in grid.findall(f"{W}gridCol")]
    total = sum(cols)
    widths.append((i, len(cols), total))
    if total > usable:
        over.append(f"table{i}={total}>{usable}")
check("Word 表格不超可打印宽度", not over,
      f"可打印宽度 {usable} twips（{usable/566.9:.2f}cm）；{len(tables)} 张表格最大 {max(w[2] for w in widths)} twips"
      + ("；超宽：" + "、".join(over) if over else ""))
fixed_rows = [h for h in body.iter(f"{W}trHeight") if h.get(f"{W}hRule") in ("exact", "atLeast")]
check("Word 无固定行高（防文字裁切重叠）", not fixed_rows,
      f"trHeight 固定行高数量 {len(fixed_rows)}；行高随内容自适应")
check("Word 无 nowrap 单元格", len(list(body.iter(f"{W}noWrap"))) == 0,
      "单元格允许自动换行，长文本不会溢出裁切")
rows = list(body.iter(f"{W}tr"))
with_cant = sum(1 for r in rows if r.find(f"{W}trPr/{W}cantSplit") is not None)
check("Word 表格行禁止跨页断行", bool(rows) and with_cant == len(rows),
      f"{len(rows)} 行全部带 <w:cantSplit/>，换页处不再把单元格内容拆到两页"
      f"（含第 4 页末尾的早餐行）")
order_bad = []
for r in rows:
    trpr = r.find(f"{W}trPr")
    if trpr is None:
        continue
    names = [c.tag.split("}")[-1] for c in trpr]
    if "cantSplit" in names and "tblHeader" in names:
        if names.index("cantSplit") > names.index("tblHeader"):
            order_bad.append(names)
check("cantSplit 在 trPr 内顺序正确", not order_bad,
      "cantSplit 排在 tblHeader 之前，符合 OOXML schema；未排序的行：" + str(len(order_bad)))
itinerary_tables = [w for w in widths if w[1] == 7]
# 7 列行程表：总宽须等于可打印宽度（允许 1-3 twips 的取整误差），
# 且最宽的「核对与来源」列须明显大于其余列——等分列会是 1474 均分。
spread_ok = bool(itinerary_tables) and all(
    abs(w[2] - usable) <= 3 for w in itinerary_tables)
col_detail = []
with zipfile.ZipFile(DOCX) as zf:
    dxml = zf.read("word/document.xml").decode("utf-8")
droot = ET.fromstring(dxml)
dbody = droot.find(f"{W}body")
for tb in dbody.findall(f"{W}tbl"):
    grid = tb.find(f"{W}tblGrid")
    cols = [int(c.get(f"{W}w")) for c in grid.findall(f"{W}gridCol")]
    if len(cols) == 7:
        col_detail.append(cols)
wide_ok = bool(col_detail) and all(max(c) > 2 * min(c) for c in col_detail)
check("Word 行程表列宽按内容分配", spread_ok and wide_ok,
      f"7 列行程表共 {len(col_detail)} 张；总宽均等于可打印宽度 {usable} twips（±3）；"
      f"最宽「核对与来源」列 {max(max(c) for c in col_detail)} twips，约为最窄列的 "
      f"{max(max(c) for c in col_detail)/min(min(c) for c in col_detail):.1f} 倍，不再等分挤压")

# ---------- 7. HTML 手机与打印 ----------
check("移动端支持", 'name="viewport"' in HTML and "@media (max-width: 680px)" in HTML,
      "viewport + 小屏横向表格滚动")
check("窄屏表格可横向滚动", "min-width: 720px" in HTML and "overflow-x: auto" in HTML
      and ".table-wrap" in HTML,
      "表格 min-width 720px，外层 .table-wrap 设 overflow-x:auto，"
      "400px 手机上 7 列表格不再挤成单字竖列")
check("打印取消表格最小宽度", "min-width: 0 !important" in HTML,
      "@media print 把 min-width 归零并按页宽铺满，打印不受屏幕样式影响")
check("打印白底黑字", "@media print" in HTML and "var(--color-print) !important" in HTML
      and "overflow: visible !important" in HTML,
      "打印取消滚动容器并强制黑字白底")
check("无脚本或主动画", "<script" not in HTML.lower() and "<animate" not in HTML.lower()
      and all(v.strip() == "none" for v in re.findall(r"animation\s*:\s*([^;!]+)", HTML)),
      "无 JavaScript、SVG 动画；CSS 仅含打印用 animation: none")
check("Word 与网页同源", HTML == STAGE_HTML,
      "DOCX 由与该 HTML 完全相同的 stage2 HTML 转换")

report = {
    "status": "pass" if not failures else "fail",
    "checks_passed": sum(1 for c in checks if c["passed"]),
    "checks_total": len(checks),
    "checks": checks,
    "failures": failures,
    "notes": [
        "未启动 headless 浏览器或 LibreOffice；Word 的实际打开与打印观感由用户核验。",
        "预算公式缓存由 editor_sdk 在工作副本上重算后单路径写回交付件；",
        "生成标识用 openpyxl 在保存时写 core properties（creator/lastModifiedBy/description），不调用插件私有标识脚本。",
        "原件备份与工作副本保留在 outputs/.预算.ref/；全程未删除任何文件。",
    ],
}
(OUT / "data" / "交付核对.json").write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
print(json.dumps({"status": report["status"], "passed": report["checks_passed"],
                  "total": report["checks_total"], "failures": failures}, ensure_ascii=False, indent=2))
