#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
layout_lint.py —— PPTX「布局/对比」确定性质量闸门（与 opc_check.py 互补）。

为什么需要这个脚本？
====================
opc_check.py 管「OPC 合规 = PowerPoint 能否干净打开」（硬阻断）。但合规的包仍可能
「能打开却难看」：文字与背景对比过低看不清、形状互相叠加、极短/无连接的残桩箭头。
这些缺陷此前只靠「soffice 截图 + 子 agent 眼检」的视觉 QA 抓——对**其他 agent / 弱模型**
不可靠（会跳过、会看漏）。

本脚本做**不依赖渲染、纯解析 OOXML** 的确定性检查：只读 slide xml 的坐标/颜色，把
「可计算」的三类缺陷在产物上拦下，给弱模型一道绕不过的防呆门槛。它**不替代**视觉 QA
（主题色/跨形状层叠/文字截断等仍需眼睛），是其前置硬门槛。

和 opc_check.py 一样：只用标准库（zipfile / xml.etree / math / re），忠实于最终消费者
（Office），不依赖任何宽容的高层库。

检查项（任一命中 → 非零退出码 + 人话问题 + 修复提示）
====================================================
A. 残桩/过短连线：连接符或 line 类形状长度 < 0.2"（端点重合/算错的残桩箭头，AI PPT 典型缺陷）。
B. 形状叠加：两个非背景、非包含、非连线形状的包围盒显著相交。
C. 低对比文字（限可靠场景）：形状有显式 solidFill 且其文字 run 有显式颜色时，二者对比
   低于阈值（大字 3:1 / 正文 4.5:1，WCAG）。

   局限（诚实声明）：不解析 theme/scheme 引用色，也不解析「文字浮于其它背景形状之上」的
   跨形状 z-order 层叠——那些由 deck_helpers 的 assertReadable / drawTitle(bg) 与视觉 QA
   覆盖。本脚本只抓「能确定、误报近零」的场景，避免像宽容库一样用噪声侵蚀信任。

用法
====
    python layout_lint.py <file.pptx>            # 校验，无缺陷退出 0，有缺陷退出 1
    python layout_lint.py <file.pptx> --verbose  # 额外打印 PASSED 明细
"""

import argparse
import math
import re
import sys
import zipfile
import xml.etree.ElementTree as ET

EMU_PER_INCH = 914400.0

# OOXML 命名空间（presentationml / drawingml），固定不变。
P = "{http://schemas.openxmlformats.org/presentationml/2006/main}"
A = "{http://schemas.openxmlformats.org/drawingml/2006/main}"

# 判定「连线/连接符」用的 prstGeom 前缀（line 类原语）。
LINE_PREFIXES = ("straightConnector", "bentConnector", "curvedConnector")

# 阈值
MIN_CONNECTOR_IN = 0.2     # 短于此判残桩连线
OVERLAP_MIN_AREA = 0.02    # 叠加最小绝对面积（in²），压住浮点/贴边噪声
OVERLAP_MIN_FRAC = 0.10    # 叠加须 > 较小形状面积的 10%，才算「显著」
BIG_BG_FRAC = 0.80         # 面积 ≥ 画布 80% 视为满铺背景，不参与叠加判定


# ──────────────── 对比度（WCAG 2.1，与 deck_helpers.mjs 同一套公式） ────────────────

def _hex_to_rgb(h: str):
    h = h.strip().lstrip("#")
    if not re.fullmatch(r"[0-9a-fA-F]{6}", h):
        raise ValueError(f"非 6 位 hex：{h}")
    return tuple(int(h[i:i + 2], 16) for i in (0, 2, 4))


def _rel_luminance(h: str) -> float:
    def chan(c: float) -> float:
        c = c / 255.0
        return c / 12.92 if c <= 0.03928 else ((c + 0.055) / 1.055) ** 2.4

    r, g, b = _hex_to_rgb(h)
    return 0.2126 * chan(r) + 0.7152 * chan(g) + 0.0722 * chan(b)


def _contrast(a: str, b: str) -> float:
    la, lb = _rel_luminance(a), _rel_luminance(b)
    hi, lo = max(la, lb), min(la, lb)
    return (hi + 0.05) / (lo + 0.05)


# ──────────────── XML 提取小工具 ────────────────

def _local(el) -> str:
    return el.tag.split("}")[-1]


def _xfrm(el):
    """返回该形状自身的 (x, y, w, h)（英寸），取不到返回 None。只看自身 xfrm，不下钻子形状。"""
    holder = el.find(P + "spPr")
    if holder is None:
        holder = el.find(P + "grpSpPr")
    xf = holder.find(A + "xfrm") if holder is not None else None
    if xf is None:
        xf = el.find(P + "xfrm")  # graphicFrame 用 p:xfrm
    if xf is None:
        return None
    off = xf.find(A + "off")
    ext = xf.find(A + "ext")
    if off is None or ext is None:
        return None
    try:
        return (
            int(off.get("x")) / EMU_PER_INCH,
            int(off.get("y")) / EMU_PER_INCH,
            int(ext.get("cx")) / EMU_PER_INCH,
            int(ext.get("cy")) / EMU_PER_INCH,
        )
    except (TypeError, ValueError):
        return None


def _name(el) -> str:
    c = el.find(".//" + P + "cNvPr")
    if c is not None and c.get("name"):
        return c.get("name")
    return _local(el)


def _is_connector(el) -> bool:
    if _local(el) == "cxnSp":
        return True
    if _local(el) == "sp":
        g = el.find(P + "spPr/" + A + "prstGeom")
        prst = g.get("prst") if g is not None else None
        if prst == "line" or (prst and prst.startswith(LINE_PREFIXES)):
            return True
    return False


def _shape_fill(el):
    sf = el.find(P + "spPr/" + A + "solidFill/" + A + "srgbClr")
    return sf.get("val") if sf is not None and sf.get("val") else None


def _low_contrast_runs(el, fill):
    """形状有显式 fill 时，逐文字 run 检查显式字色与 fill 的对比，返回不达标项。"""
    out = []
    for r in el.findall(".//" + A + "r"):
        rpr = r.find(A + "rPr")
        if rpr is None:
            continue
        clr = rpr.find(A + "solidFill/" + A + "srgbClr")
        if clr is None or not clr.get("val"):
            continue  # 主题/方案色不在 v1 范围（局限已在文首声明）
        run_color = clr.get("val")
        try:
            ratio = _contrast(run_color, fill)
        except ValueError:
            continue
        try:
            sz = int(rpr.get("sz")) if rpr.get("sz") else 0
        except ValueError:
            sz = 0
        bold = rpr.get("b") in ("1", "true")
        large = sz >= 1800 or (sz >= 1400 and bold)  # WCAG 大字：≥18pt 或 ≥14pt 粗体
        min_ratio = 3.0 if large else 4.5
        if ratio < min_ratio:
            t = r.find(A + "t")
            snippet = (t.text or "").strip()[:20] if t is not None else ""
            out.append((run_color, fill, ratio, min_ratio, snippet))
    return out


def check_layout(path: str, verbose: bool = False) -> list:
    """对 pptx 做布局/对比检查，返回问题列表（空 = 无可计算缺陷）。"""
    problems = []

    if not zipfile.is_zipfile(path):
        return [f"不是合法的 zip/OOXML 包：{path}"]

    with zipfile.ZipFile(path, "r") as zf:
        names = zf.namelist()

        # 画布尺寸（取不到则按 LAYOUT_WIDE 13.333"×7.5" 兜底）。
        slide_w, slide_h = 13.333, 7.5
        if "ppt/presentation.xml" in names:
            try:
                pres = ET.fromstring(zf.read("ppt/presentation.xml"))
                sz = pres.find(P + "sldSz")
                if sz is not None and sz.get("cx") and sz.get("cy"):
                    slide_w = int(sz.get("cx")) / EMU_PER_INCH
                    slide_h = int(sz.get("cy")) / EMU_PER_INCH
            except (ET.ParseError, ValueError):
                pass
        slide_area = slide_w * slide_h

        slide_names = sorted(
            (n for n in names if re.fullmatch(r"ppt/slides/slide\d+\.xml", n)),
            key=lambda n: int(re.search(r"(\d+)", n.rsplit("/", 1)[-1]).group(1)),
        )

        for sn in slide_names:
            try:
                root = ET.fromstring(zf.read(sn))
            except ET.ParseError:
                continue  # 良构由 opc_check 负责，这里跳过
            tree = root.find(P + "cSld/" + P + "spTree")
            if tree is None:
                continue
            label = sn.rsplit("/", 1)[-1]
            rects = []  # 非连线、非满铺背景形状的 (x, y, w, h, name)

            for el in list(tree):
                if _local(el) not in ("sp", "cxnSp", "pic", "graphicFrame", "grpSp"):
                    continue
                box = _xfrm(el)

                # ── A. 残桩/过短连线 ──
                if _is_connector(el):
                    if box is not None:
                        length = math.hypot(box[2], box[3])
                        if length < MIN_CONNECTOR_IN:
                            problems.append(
                                f'{label}: 残桩/过短连线「{_name(el)}」长度 {length:.3f}" '
                                f'< {MIN_CONNECTOR_IN}"（端点几乎重合，疑似无连接的残桩箭头）'
                            )
                    continue  # 连线不参与叠加判定（穿过形状属正常）

                # ── C. 低对比文字（仅 sp，限显式色对） ──
                if _local(el) == "sp":
                    fill = _shape_fill(el)
                    if fill:
                        for rc, fc, ratio, minr, snippet in _low_contrast_runs(el, fill):
                            tip = f"「{snippet}…」" if snippet else ""
                            problems.append(
                                f"{label}: 低对比文字{tip}字色 {rc} / 底色 {fc} = "
                                f"{ratio:.2f}:1 < {minr}:1（看不清；改字色或底色，用 inkFor(bg)）"
                            )

                # ── B. 收集叠加候选 rect ──
                if box is not None:
                    x, y, w, h = box
                    if w * h >= BIG_BG_FRAC * slide_area:
                        continue  # 满铺背景，不参与叠加
                    rects.append((x, y, w, h, _name(el)))

            # ── B. 两两包围盒比对 ──
            for i in range(len(rects)):
                ax, ay, aw, ah, an = rects[i]
                for j in range(i + 1, len(rects)):
                    bx, by, bw, bh, bn = rects[j]
                    ix, iy = max(ax, bx), max(ay, by)
                    ix2, iy2 = min(ax + aw, bx + bw), min(ay + ah, by + bh)
                    if ix2 <= ix or iy2 <= iy:
                        continue  # 不相交
                    # 包含关系 = 正常（如卡片内文字），跳过
                    a_in_b = ax >= bx and ay >= by and ax + aw <= bx + bw and ay + ah <= by + bh
                    b_in_a = bx >= ax and by >= ay and bx + bw <= ax + aw and by + bh <= ay + ah
                    if a_in_b or b_in_a:
                        continue
                    inter = (ix2 - ix) * (iy2 - iy)
                    smaller = min(aw * ah, bw * bh)
                    if inter > OVERLAP_MIN_AREA and inter > OVERLAP_MIN_FRAC * smaller:
                        problems.append(
                            f'{label}: 形状叠加「{an}」×「{bn}」重叠 {inter:.2f} in²'
                            f"（约占较小形状 {inter / smaller * 100:.0f}%；拉开间距 ≥0.3\"）"
                        )

        if verbose and not problems:
            print("PASSED 布局/对比检查：无残桩连线 / 无显著叠加 / 无低对比文字")

    return problems


def main() -> int:
    parser = argparse.ArgumentParser(
        description="PPTX 布局/对比 确定性质量闸门（与 opc_check.py 互补，仅依赖标准库）"
    )
    parser.add_argument("file", help="要校验的 .pptx 文件")
    parser.add_argument("-v", "--verbose", action="store_true", help="打印 PASSED 明细")
    args = parser.parse_args()

    problems = check_layout(args.file, verbose=args.verbose)
    if problems:
        print(f"布局/对比检查 FAILED —— {args.file} 存在 {len(problems)} 处问题：")
        for p in problems:
            print("  - " + p)
        print(
            "提示：对比用 deck_helpers 的 inkFor(bg)/assertReadable；"
            "连线用 connect(from, to)；叠加拉开间距 ≥0.3\"。"
            "（本检查不替代视觉 QA。）"
        )
        return 1

    print(f"布局/对比检查 PASSED —— {args.file} 无可计算的布局/对比缺陷（视觉 QA 仍需进行）。")
    return 0


if __name__ == "__main__":
    sys.exit(main())
