#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
text_readability_pixel.py —— 像素级「文字压图可读性」确定性闸门（ppt 视觉门专用）。

为什么需要这个脚本（2026-07-02 逐页体检根因 ⑤）
====================
既有对比度检查（export mjs 的 resolveBg → layout_balance 的 lowContrast）只沿 DOM 找 CSS
background-color——文字压在**背景图片**上时拿到的是页面底色：深色图页刷出大量「白字/浅底 1.05」
假阳，而真正压图不可读处（标题横穿明暗跨界照片）拿到的也是同一个错误数字。CSS 层面**物理上**
测不出图片背衬的可读性，必须采真实像素。

工作方式
========
读 export_pptx_from_html.mjs `--measure-only --with-bg-shots` 的产物：
  - layout-report.json 的 slides[].textRuns（文本原始 px 矩形 + 颜色 + fgParent）
  - slide-NN-background.png（背景态整页截图：隐前景块 + 隐全部文本 = 直接压背景层的文字底下的真实背衬）
  - slide-NN-foreground.png（foreground 态整页截图：隐全部文字、卡片/SVG/渐变/图片原样渲染
    = 卡内/前景块内文字底下的真实背衬。2026-07-03 新增——此前 fgParent 非空的文本被整体跳过，
    真机实测占比高达 81%，深底深字/压卡不可读几乎是检测盲区；CSS 层 resolveBg 也测不准同类场景
    （渐变会跳过继续往上找、读不懂 SVG fill）。两张截图同源同机制，只是隐藏对象不同。）
对每条文本：`fgParent` 为空 → 从背景截图采样；`fgParent` 非空 → 从 foreground 截图采样
（该文本本就嵌在某前景块/卡片里，foreground 截图里那块内容原样可见，直接是它的真实背衬，
无需再猜测卡片颜色）。在其矩形内网格采样像素，逐点算 WCAG 对比度：
  - 失败占比 ≥ FAIL_FRAC_ERROR → ERROR（文字实质不可读）
  - 失败占比 ≥ FAIL_FRAC_WARN  → WARNING（部分区域可读性差）
  - 分段局部判定（2026-07-03）：矩形横切 6 段逐段判，任一段失败率 ≥70% →
    【文字局部压图不可读】ERROR——治「列表行一半压平板黑边框、另一半净区，整框平均被稀释到
    连 WARNING 都不报」（真机 06 页）；窄文本（段内采样列不足）不分段，防小样本误报。
  - 系统性同色归组（2026-07-03）：ERROR 里同一文字颜色出现 ≥3 次时追加一行归组提示——真机复盘
    27 处 ERROR 里 15+ 处共享同一 VI 强调色 CSS 变量（`.t-eyebrow`/`.label` 之类多处复用），
    逐条加局部 scrim 的修复策略在有限轮数内修不完；提示指向「改一次共享 CSS 规则/变量能同时
    清零全部同色实例」，纯汇总已收集数据、不新增判断。
报错带 页 · 文本 · 归一化矩形 · 实测数据 + 修法建议（加 scrim / 移净区 / 换字色）。
`slide-NN-foreground.png` 缺失（旧 report / 未传 `--with-bg-shots`）时，fgParent 非空的文本
优雅降级为跳过（与改前行为一致，不新增失败模式）。

依赖：Pillow（ppt 工作流 stage_extract 已依赖 PIL，与其同环境）。缺 PIL / 缺截图 / 缺
textRuns 字段（旧 report）一律**响亮 SKIP 但 exit 0**（fail-open：像素检查是增强层，
缺依赖不阻断工作流；SKIP 行会进 visual_quality_report 让人看见「本轮没做像素检查」）。

用法：python text_readability_pixel.py <workdir>   # 含 layout-report.json + slide-NN-background.png
"""

import argparse
import json
import os
import re
import sys
from collections import Counter

# 采样与阈值（对照 2026-07-02 真机 deck 23 页逐页标定：02/08/12/15/23 该抓、03/22 像素实测可读不误报、
# 04/07/13/16/21 章节页装饰序号不误伤）
SAMPLE_GRID_W = 48        # 矩形内横向最多采样列数
SAMPLE_GRID_H = 16        # 纵向最多采样行数
CONTRAST_FLOOR = 3.0      # 放映级大字 AA 阈（与 layout_balance lowContrast 同口径）
FAIL_FRAC_ERROR = 0.35    # ≥35% 采样点低于阈 → ERROR（文字实质不可读）
FAIL_FRAC_WARN = 0.15     # ≥15% → WARNING
MIN_TEXT_LEN = 2          # 单字符/空串不查（装饰符）
MIN_RECT_PX = 24          # 矩形宽或高小于此不查（图钉级小元素）
DECOR_NUM_FONT = 96       # 纯数字 ≤3 字符且字号 ≥ 此值 = 章节页水印式装饰序号（低对比是设计意图），豁免
FG_COVER_SKIP = 0.60      # 文本矩形被某前景块（媒体图/卡）盖住 ≥60% → 真实背衬是该前景块而非背景图，
#   背景截图采样会错测（slide12 SCENE 文字底下是图块）→ 跳过；文字×前景的碰撞由重叠门负责。
# 分段局部判定（2026-07-03 真机 06 页根因：列表行一半压在平板黑边框上完全不可读，另一半是净区——
# 整框平均后失败率被稀释到阈下，连 WARNING 都没报）。把矩形横切 SEG_COUNT 段逐段判：任一段失败率
# ≥ SEG_FAIL_FRAC 即【文字局部压图不可读】ERROR。段内采样列数不足（窄文本）不做分段判定，防小样本误报。
SEG_COUNT = 6             # 横向分段数（6 段：单段全挂时整框最低 0.7/6≈11.7%，低于 WARN 线的局部遮挡也抓得到）
SEG_FAIL_FRAC = 0.70      # 单段失败率 ≥70% → 局部实质不可读
SEG_MIN_COLS = 6          # 每段至少采样列数（gw ≥ 36 才分段；窄文本整框判定已足够）
SYSTEMIC_COLOR_MIN_COUNT = 3  # 同一文字颜色的 ERROR 数达此值 → 判定系统性 CSS 变量问题，追加归组提示


def _parse_color(c):
    """rgb()/rgba()/#hex → (r,g,b) 0-255；解析不了返回 None。"""
    if not isinstance(c, str):
        return None
    m = re.match(r"rgba?\(([^)]+)\)", c.strip())
    if m:
        parts = [p.strip() for p in m.group(1).split(",")]
        try:
            vals = [float(p) for p in parts[:3]]
        except ValueError:
            return None
        if len(vals) >= 3:
            return tuple(min(255, max(0, int(v))) for v in vals)
        return None
    m = re.match(r"^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$", c.strip())
    if m:
        h = m.group(1)
        if len(h) == 3:
            h = "".join(ch * 2 for ch in h)
        return tuple(int(h[i:i + 2], 16) for i in (0, 2, 4))
    return None


def _rel_lum(rgb):
    """WCAG 相对亮度（0-1，含 gamma 线性化）。"""
    def f(v):
        c = v / 255.0
        return c / 12.92 if c <= 0.03928 else ((c + 0.055) / 1.055) ** 2.4
    r, g, b = rgb[:3]
    return 0.2126 * f(r) + 0.7152 * f(g) + 0.0722 * f(b)


def _contrast(l1, l2):
    hi, lo = (l1, l2) if l1 >= l2 else (l2, l1)
    return (hi + 0.05) / (lo + 0.05)


def _fg_cover_fraction(run, fg_rects, width, height):
    """文本 px 矩形被前景块（归一化 rect）盖住的最大比例。"""
    try:
        rx, ry, rw, rh = (float(run[k]) for k in ("x", "y", "w", "h"))
    except (KeyError, TypeError, ValueError):
        return 0.0
    if rw <= 0 or rh <= 0 or width <= 0 or height <= 0:
        return 0.0
    nx, ny, nw, nh = rx / width, ry / height, rw / width, rh / height
    best = 0.0
    for fr in fg_rects:
        if not isinstance(fr, dict):
            continue
        try:
            fx, fy, fw, fh = (float(fr.get(k) or 0.0) for k in ("x", "y", "w", "h"))
        except (TypeError, ValueError):
            continue
        iw = min(nx + nw, fx + fw) - max(nx, fx)
        ih = min(ny + nh, fy + fh) - max(ny, fy)
        if iw > 0 and ih > 0:
            best = max(best, (iw * ih) / (nw * nh))
    return best


def _fmt_rect_px(run, width, height):
    try:
        return (
            f"[x{run['x'] / width:.2f} y{run['y'] / height:.2f} "
            f"w{run['w'] / width:.2f} h{run['h'] / height:.2f}]"
        )
    except (KeyError, TypeError, ZeroDivisionError):
        return ""


def check_readability(workdir, report_path=None, verbose=False):
    """返回 (problems, warnings, skips)。缺依赖/缺产物 → 全空 + skips 说明（fail-open）。"""
    problems, warnings, skips = [], [], []
    # ERROR 项的文字颜色（并行于 problems，供归组提示用；2026-07-03，见下方归组段落）。
    problem_colors = []

    try:
        from PIL import Image  # noqa: PLC0415  （可选依赖，缺则响亮降级）
    except ImportError:
        skips.append("Pillow(PIL) 未安装：跳过像素级文字可读性检查（本轮未做像素检查）。")
        return problems, warnings, skips

    report_path = report_path or os.path.join(workdir, "layout-report.json")
    if not os.path.isfile(report_path):
        skips.append(f"{report_path} 不存在：先跑 export --measure-only --with-bg-shots。")
        return problems, warnings, skips
    try:
        with open(report_path, "r", encoding="utf-8") as f:
            report = json.load(f)
    except (OSError, json.JSONDecodeError) as exc:
        skips.append(f"layout-report.json 解析失败：{exc}")
        return problems, warnings, skips

    width = report.get("width") or 1920
    height = report.get("height") or 1080

    for slide in report.get("slides") or []:
        idx = slide.get("index")
        label = slide.get("label") or f"slide {idx}"
        runs = slide.get("textRuns")
        if runs is None:
            skips.append(f"{label}：report 无 textRuns 字段（旧 measure 产物），跳过。")
            continue
        shot = os.path.join(workdir, f"slide-{int(idx):02d}-background.png")
        if not os.path.isfile(shot):
            skips.append(f"{label}：缺 {os.path.basename(shot)}（measure 未带 --with-bg-shots），跳过。")
            continue
        try:
            img = Image.open(shot).convert("RGB")
        except OSError as exc:
            skips.append(f"{label}：背景截图打开失败（{exc}），跳过。")
            continue
        iw, ih = img.size
        sx = iw / width
        sy = ih / height
        # foreground 态截图（文字隐藏、卡片/SVG/渐变原样渲染）：给 fgParent 非空的文本采真实背衬。
        # 缺失（旧 report/未传 --with-bg-shots）→ 这类文本优雅降级跳过，不报 skip（沿用改前行为，避免刷屏）。
        fg_shot = os.path.join(workdir, f"slide-{int(idx):02d}-foreground.png")
        fg_img = None
        if os.path.isfile(fg_shot):
            try:
                fg_img = Image.open(fg_shot).convert("RGB")
            except OSError:
                fg_img = None
        balance = slide.get("balance") or {}
        # 前景块矩形（媒体图 + 卡/底板）：fgParent=null 的文本被它们盖住时真实背衬不是背景图
        fg_rects = list(balance.get("mediaRects") or [])
        fg_rects += [c.get("rect") for c in (balance.get("cards") or []) if isinstance(c, dict)]

        for run in runs:
            text = (run.get("text") or "").strip()
            if len(text) < MIN_TEXT_LEN:
                continue
            if text.isdigit() and len(text) <= 3 and (run.get("fontSize") or 0) >= DECOR_NUM_FONT:
                continue  # 章节页水印式大号序号（01-05）：低对比是设计意图，不是缺陷
            has_fg_parent = bool(run.get("fgParent"))
            if has_fg_parent:
                if fg_img is None:
                    continue  # 无 foreground 截图，优雅降级跳过
                sample_img, samp_sx, samp_sy = fg_img, fg_img.size[0] / width, fg_img.size[1] / height
            else:
                if fg_rects and _fg_cover_fraction(run, fg_rects, width, height) >= FG_COVER_SKIP:
                    continue  # 底下垫着前景图块/卡但 DOM 未挂 fgParent：真实背衬非背景图；碰撞类问题由重叠门负责
                sample_img, samp_sx, samp_sy = img, sx, sy
            color = _parse_color(run.get("color"))
            if color is None:
                continue
            try:
                x, y, w, h = (float(run[k]) for k in ("x", "y", "w", "h"))
            except (KeyError, TypeError, ValueError):
                continue
            if w < MIN_RECT_PX or h < MIN_RECT_PX:
                continue
            # 裁剪到画布内（越界文本归超画布门管）；缩放系数按实际采样图自身尺寸算（foreground/background
            # 截图理论同尺寸，但不假设——各自图自己算最稳妥）。
            x0 = max(0.0, x) * samp_sx
            y0 = max(0.0, y) * samp_sy
            x1 = min(width, x + w) * samp_sx
            y1 = min(height, y + h) * samp_sy
            if x1 - x0 < 2 or y1 - y0 < 2:
                continue
            crop = sample_img.crop((int(x0), int(y0), int(x1), int(y1)))
            # 缩到采样网格：几百个点足够统计，帧级快
            gw = max(1, min(SAMPLE_GRID_W, crop.width))
            gh = max(1, min(SAMPLE_GRID_H, crop.height))
            crop = crop.resize((gw, gh))
            text_lum = _rel_lum(color)
            fails = 0
            worst = None
            total = gw * gh
            col_fails = [0] * gw  # 逐列失败计数（行主序 getdata：i % gw = 列号），供分段局部判定
            for i, px in enumerate(crop.getdata()):
                ratio = _contrast(text_lum, _rel_lum(px))
                if ratio < CONTRAST_FLOOR:
                    fails += 1
                    col_fails[i % gw] += 1
                    if worst is None or ratio < worst:
                        worst = ratio
            frac = fails / total if total else 0.0
            # 分段局部判定：任一横段失败率 ≥ SEG_FAIL_FRAC = 局部实质不可读（整框平均会稀释它）。
            seg_hit = None
            if gw >= SEG_MIN_COLS * SEG_COUNT and gh > 0:
                for s in range(SEG_COUNT):
                    c0 = s * gw // SEG_COUNT
                    c1 = (s + 1) * gw // SEG_COUNT
                    seg_total = (c1 - c0) * gh
                    if seg_total <= 0:
                        continue
                    seg_frac = sum(col_fails[c0:c1]) / seg_total
                    if seg_frac >= SEG_FAIL_FRAC:
                        seg_hit = (s + 1, seg_frac)
                        break
            if verbose:
                print(f"  {label} · 「{text[:16]}」 fail={frac*100:.0f}% worst={worst or 0:.2f}"
                      + (f" seg{seg_hit[0]}={seg_hit[1]*100:.0f}%" if seg_hit else ""))
            fix_hint = (
                f"  ｜可参考修法（非强制）：文字下加局部 scrim/暗角底板（紧贴文字，禁大面积白卡）"
                f" → 或把文字移动到背景净区 → 或换字色（深底白字/浅底深墨字）"
            )
            if frac >= FAIL_FRAC_WARN:
                seg_note = (
                    f"；左起第 {seg_hit[0]}/{SEG_COUNT} 段 {seg_hit[1]*100:.0f}% 局部实质不可读"
                    if seg_hit and frac < FAIL_FRAC_ERROR else ""
                )
                msg = (
                    f"【文字压图不可读】{label} · 「{text[:16]}」{_fmt_rect_px(run, width, height)}"
                    f" · 实测 {frac*100:.0f}% 采样点对比度 <{CONTRAST_FLOOR}（最差 {worst:.2f}，文字 {run.get('color')}{seg_note}）"
                    + fix_hint
                )
                if frac >= FAIL_FRAC_ERROR or seg_hit:
                    problems.append(msg)
                    problem_colors.append(run.get("color"))
                else:
                    warnings.append(msg)
            elif seg_hit:
                problems.append(
                    f"【文字局部压图不可读】{label} · 「{text[:16]}」{_fmt_rect_px(run, width, height)}"
                    f" · 左起第 {seg_hit[0]}/{SEG_COUNT} 段 {seg_hit[1]*100:.0f}% 采样点对比度 <{CONTRAST_FLOOR}"
                    f"（整框仅 {frac*100:.0f}%——局部遮挡被整框平均稀释，文字 {run.get('color')}）"
                    + fix_hint
                )
                problem_colors.append(run.get("color"))

    # 系统性同色归组提示（2026-07-03 真机复盘：27 处 ERROR 里 15+ 处共享同一 CSS 变量取值，
    # 逐条加局部 scrim 的修复策略在有限轮数内根本修不完；真正的修法是改一次共享 CSS 规则/变量）。
    # 纯汇总已收集的 problem_colors，不新增判断/猜测——只是把「这些问题其实是一件事」的信号显式标出来。
    color_counts = Counter(c for c in problem_colors if c)
    for color, count in color_counts.most_common():
        if count >= SYSTEMIC_COLOR_MIN_COUNT:
            problems.append(
                f"⚠️ {count} 处文字压图问题共享同一文字颜色 {color}：疑似同一 CSS 变量/class 系统性问题"
                f"（如 `.t-eyebrow`/`.label` 之类被多处复用的强调色），建议**一次性改共享 CSS 规则/变量**"
                f"（改深该颜色，或给该 class 统一加色块/半透明底），而非逐条加局部 scrim——"
                f"逐条修在有限轮数内修不完，改一次能同时清零全部同色实例。"
            )

    return problems, warnings, skips


def main() -> int:
    parser = argparse.ArgumentParser(
        description="像素级文字压图可读性闸门（读 measure-only --with-bg-shots 产物；缺依赖响亮 SKIP 不阻断）"
    )
    parser.add_argument("workdir", help="含 layout-report.json + slide-NN-background.png 的目录")
    parser.add_argument("--report", help="layout-report.json 路径（默认 <workdir>/layout-report.json）")
    parser.add_argument("-v", "--verbose", action="store_true", help="打印每条文本的采样明细")
    args = parser.parse_args()

    problems, warnings, skips = check_readability(args.workdir, report_path=args.report, verbose=args.verbose)

    for s in skips:
        print("SKIP: " + s)
    for w in warnings:
        print("WARNING: " + w)
    if problems:
        print(f"文字压图可读性检查 FAILED —— {len(problems)} 处文字实质不可读：")
        for p in problems:
            print("  - " + p)
        return 1
    print("文字压图可读性检查 PASSED"
          + ("（部分页跳过，见 SKIP）" if skips else "")
          + f"（WARNING {len(warnings)} 条）")
    return 0


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