#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""检查生成后的 deck.html 是否退回卡片墙/表格墙/文字墙。

它不替代 layout_balance.py。layout_balance 管越界、重叠、截图夹带文本等硬几何问题；
本脚本只管产品详情页式 PPT 的结构性视觉退化。
"""

from __future__ import annotations

import argparse
from collections import Counter
import json
import re
import sys
from html.parser import HTMLParser
from pathlib import Path


SECTION_RE = re.compile(r"<section\b[\s\S]*?</section>", re.I)
LABEL_RE = re.compile(r"data-screen-label=[\"']([^\"']+)", re.I)
# 讲稿 aside（<aside class="speaker-notes" hidden>…</aside>，display:none 不渲染、导出进 PPT 备注栏）：
# 其正文是演讲论证，提到「表格/矩阵/card」是在讲内容不是页面布局——所有源码级扫描前先剥掉。
SPEAKER_NOTES_RE = re.compile(
    r"<aside\b[^>]*class=[\"'][^\"']*speaker-notes[^\"']*[\"'][\s\S]*?</aside>", re.I
)
CARD_RE = re.compile(r"card|panel|tile|module|stat-card|dark-card|content-card", re.I)
TABLE_RE = re.compile(r"<table\b|compare-grid|matrix|table-", re.I)
BG_RE = re.compile(r"edit-bg|bg-img|background-image\s*:|url\(", re.I)
OBJECT_FILL_RE = re.compile(r"object-fit\s*:\s*fill", re.I)
IMAGE_FRAME_RE = re.compile(r"(?:src-figure|fig-fill|image-tile|mosaic|gallery|product-visual|hero-visual|closeup)", re.I)
DATA_VISUAL_RE = re.compile(r"<svg\b|chart|axis|bar-|bars|line-chart|sparkline|plot|meter|gauge|timeline|data-viz", re.I)
STRONG_DATA_VISUAL_RE = re.compile(r"<svg\b|bar-chart|line-chart|axis|parameter-axis|data-viz|chart|bars|plot|meter|gauge", re.I)
CHART_MARKER_RE = re.compile(r"bar-chart|line-chart|axis|parameter-axis|data-viz|chart|bars|plot|meter|gauge", re.I)
BAD_FRAME_CLASS_RE = re.compile(r"(?:src-figure|fig-fill|image-tile|mosaic|gallery|product-visual|hero-visual|closeup)", re.I)
BAD_FRAME_STYLE_RE = re.compile(
    r"background\s*:\s*(?:#fff|white|var\(--surface\)|rgba\(255,\s*255,\s*255)"
    r"|padding\s*:|border\s*:",
    re.I,
)
IMG_SRC_RE = re.compile(r"<img\b[^>]*?(?<!\.)\bsrc=[\"']([^\"']+)[\"']", re.I)
BG_IMG_RE = re.compile(r"<img\b[^>]*class=[\"'][^\"']*bg-img[^\"']*[\"']", re.I)
CLASS_RE = re.compile(r"class=[\"']([^\"']+)[\"']", re.I)
SOURCE_FILE_RE = re.compile(r"data-source-file=[\"']([^\"']+)[\"']", re.I)
AI_BACKGROUND_ONLY_RE = re.compile(r"^ai_p\d+\.(?:png|jpg|jpeg|webp)$", re.I)
FONT_SIZE_RE = re.compile(r"font-size\s*:\s*(\d+(?:\.\d+)?)px", re.I)
SYSTEMIC_FONT_SIZE_MIN_COUNT = 3  # 同一错误字号的 ERROR 数达此值 → 判定系统性重复值，追加归组提示
SVG_TEXT_SIZE_RE = re.compile(r"<text\b[^>]*font-size=[\"'](\d+(?:\.\d+)?)[\"']", re.I)
CONNECTOR_RE = re.compile(r"<(?:line|path|polyline)\b", re.I)
DIAGRAM_NODE_RE = re.compile(
    r"(?:diagram-node|data-node|flow-node|flow-step|question-node|answer-node|class=[\"'][^\"']*(?:node|step|chip|pill))",
    re.I,
)
# 纯装饰性 SVG（layout-composition.md §0.8「装饰几何（连线/节点/分隔光带）」明确要求每页≥1视觉
# 元素时可用它填充空页；ppt.yaml 要求统一命名 `class="vi-deco"`）：其内部的 line/path/polyline
# 只是几何点缀，不是图表/流程图连线，不该被孤立连线检查盯上——否则跟"没配图的页也要有装饰几何"
# 这条指导自相矛盾。2026-07-06 真机复盘：模型在提示词未强制命名前自造了 `crosshair-svg` 这个
# 不同名字表达同一种纯装饰意图，因此这里额外接受几个同义命名兜底（提示词已同步要求统一用 vi-deco，
# 这里的宽松匹配是双保险，不能替代提示词约定）。
DECOR_SVG_RE = re.compile(
    r"<svg\b[^>]*\bclass=[\"'][^\"']*\b(?:vi-deco|crosshair-svg|deco-svg|ambient-svg)\b[^\"']*[\"'][^>]*>.*?</svg>",
    re.I | re.S,
)
# 2026-07-07 真机三度复盘（同一"命名约定不可靠"主题的第三种表现）：这次是一份**真实、完整**的
# 对比图表——4 组 `<rect>+<text>` 标签节点（"记录主体→机器"/"空间覆盖→360°"等）用带箭头的
# `<line>` 连到右侧的另一组文字标签，节点内容齐全，不是缺节点的孤立连线；但这些 `<rect>` 没有
# 任何 `class="...node/step/chip/pill..."` 之类的语义类名，DIAGRAM_NODE_RE 纯靠类名匹配抓不到，
# 照样误报"孤立连线缺节点"。结构特征识别：连线所在的 SVG 里如果同时有形状元素（`<rect>`/
# `<circle>`）和足够数量的 `<text>` 标签（≥2，一条孤立装饰线不会无缘无故配文字标签），就是
# 真实数据节点存在的可靠信号，不依赖任何命名约定。
SVG_SHAPE_RE = re.compile(r"<(?:rect|circle)\b", re.I)
SVG_TEXT_LABEL_RE = re.compile(r"<text\b", re.I)


def _has_labeled_shape_nodes(scope: str) -> bool:
    return bool(SVG_SHAPE_RE.search(scope)) and len(SVG_TEXT_LABEL_RE.findall(scope)) >= 2


# 2026-07-06 真机三度复盘：模型这次连 class 都没写（`<svg viewBox="0 0 600 600" style="...">`），
# 命名约定型豁免（DECOR_SVG_RE）天生管不到。改用结构特征识别：径向准线/雷达式装饰的标志性几何是
# "多个圆共享同一圆心"（同心圆），这是纯装饰的可靠指纹——真正的图表/流程图几乎不会用同心圆做
# 核心结构。不依赖任何命名约定，模型不管怎么起名/起不起名都能识别。
SVG_BLOCK_RE = re.compile(r"<svg\b[^>]*>.*?</svg>", re.I | re.S)
CIRCLE_CENTER_RE = re.compile(r"<circle\b[^>]*\bcx=[\"']([\d.]+)[\"'][^>]*\bcy=[\"']([\d.]+)[\"']", re.I)


def _strip_concentric_decorative_svgs(text: str) -> str:
    def _replace(m: re.Match) -> str:
        block = m.group(0)
        centers = Counter(CIRCLE_CENTER_RE.findall(block))
        if centers and centers.most_common(1)[0][1] >= 2:
            return ""  # ≥2 个圆共享同一圆心 = 同心圆装饰，整块视为纯装饰剔除
        return block

    return SVG_BLOCK_RE.sub(_replace, text)
BACKPLATE_CLASS_RE = re.compile(r"(?:frost|glass|caption|callout|pill|panel|card|surface|copy-box|text-box)", re.I)
STYLE_ATTR_RE = re.compile(r"style=[\"']([^\"']+)[\"']", re.I)
WIDTH_RE = re.compile(r"(?:^|;)\s*(?:width|max-width|min-width)\s*:\s*(\d+(?:\.\d+)?)px", re.I)
HEIGHT_RE = re.compile(r"(?:^|;)\s*(?:height|max-height|min-height)\s*:\s*(\d+(?:\.\d+)?)px", re.I)
WRITING_MODE_RE = re.compile(r"writing-mode\s*:\s*(?:vertical|sideways)", re.I)
GRID_NARROW_RE = re.compile(r"grid-template-columns\s*:[^;]*(?:\b\d{1,2}px\b|\b0\.\d+fr\b)", re.I)
TEXT_COLOR_RE = re.compile(r"(?:^|;)\s*color\s*:\s*(#[0-9a-f]{3,6}|rgb\([^)]+\))", re.I)
BG_COLOR_RE = re.compile(r"(?:^|;)\s*background(?:-color)?\s*:\s*(#[0-9a-f]{3,6}|rgb\([^)]+\)|rgba\([^)]+\)|black|white)", re.I)
IMAGE_LED_STYLES = {
    "product-hero",
    "feature-theater",
    "detail-closeup",
    "scenario-fullbleed",
    "chapter-cinematic",
    "quote-focus",
}


class TextExtractor(HTMLParser):
    def __init__(self):
        super().__init__(convert_charrefs=True)
        self.parts: list[str] = []
        self._skip = 0

    def handle_starttag(self, tag, attrs):
        if tag.lower() in {"script", "style"}:
            self._skip += 1

    def handle_endtag(self, tag):
        if tag.lower() in {"script", "style"} and self._skip:
            self._skip -= 1

    def handle_data(self, data):
        if not self._skip:
            self.parts.append(data)

    def text(self) -> str:
        return re.sub(r"\s+", " ", " ".join(self.parts)).strip()


def load_design(path: str | None):
    if not path:
        return {}
    try:
        data = json.loads(Path(path).read_text(encoding="utf-8-sig"))
    except Exception:
        return {}
    pages = data.get("pages") if isinstance(data, dict) else []
    result = {}
    for page in pages if isinstance(pages, list) else []:
        if isinstance(page, dict):
            result[int(page.get("page") or len(result) + 1)] = page
    return result


def load_image_report(path: str | None):
    if not path:
        return {"degraded": {}, "fallbacks": {}}
    try:
        data = json.loads(Path(path).read_text(encoding="utf-8-sig"))
    except Exception:
        return {"degraded": {}, "fallbacks": {}}
    degraded = {}
    fallbacks = {}
    for item in data.get("degraded", []) if isinstance(data, dict) else []:
        if not isinstance(item, dict):
            continue
        file = item.get("file")
        if not file:
            continue
        degraded[str(file)] = item
        fallbacks[str(file)] = item.get("fallback")
    return {"degraded": degraded, "fallbacks": fallbacks}


def load_source_plan(path: str | None):
    if not path:
        return {"enhanced": {}, "sources": {}, "plan_images": {}}
    try:
        data = json.loads(Path(path).read_text(encoding="utf-8-sig"))
    except Exception:
        return {"enhanced": {}, "sources": {}, "plan_images": {}}
    enhanced = {}
    sources = {}
    plan_images = {}
    entries = data.get("enhance_entries", []) if isinstance(data, dict) else []
    for item in entries if isinstance(entries, list) else []:
        if not isinstance(item, dict):
            continue
        file = item.get("file")
        source = item.get("source_file")
        if file:
            enhanced[str(file)] = item
        if source:
            sources[str(source)] = item
    # 逐图规划条目（usage_intent / enhance_required / has_embedded_text / target_layer）：
    # 供「原图带字禁用」「证据图禁做背景」两项确定性检查（2026-07-02 逐页体检裁决）。
    images = data.get("images", []) if isinstance(data, dict) else []
    for item in images if isinstance(images, list) else []:
        if isinstance(item, dict) and item.get("file"):
            plan_images[str(item["file"])] = item
    return {"enhanced": enhanced, "sources": sources, "plan_images": plan_images}


def section_text(section: str) -> str:
    parser = TextExtractor()
    parser.feed(section)
    parser.close()
    return parser.text()


def _short_text(html: str) -> str:
    parser = TextExtractor()
    parser.feed(html)
    parser.close()
    return parser.text()


def page_number(label: str | None, index: int) -> int:
    if label:
        m = re.match(r"\s*(\d+)", label)
        if m:
            return int(m.group(1))
    return index


def _is_remote_or_data(src: str) -> bool:
    return src.startswith(("http://", "https://", "data:", "file:"))


def _missing_assets(section: str, deck_dir: Path) -> list[str]:
    if not (deck_dir / "assets").exists():
        return []
    missing = []
    for src in IMG_SRC_RE.findall(section):
        if _is_remote_or_data(src):
            continue
        path = (deck_dir / src).resolve()
        try:
            path.relative_to(deck_dir.resolve())
        except ValueError:
            continue
        if not path.exists():
            missing.append(src)
    return missing


def _basename(src: str) -> str:
    src = src.split("#", 1)[0].split("?", 1)[0]
    return Path(src).name


def _asset_name(value: str) -> str:
    if not value:
        return ""
    return _basename(str(value).strip())


def _section_srcs(section: str) -> list[str]:
    return [_basename(src) for src in IMG_SRC_RE.findall(section)]


def _bg_srcs(section: str) -> list[str]:
    out = []
    for tag in re.findall(r"<img\b[^>]*>", section, re.I):
        cls = CLASS_RE.search(tag)
        if not cls or "bg-img" not in cls.group(1):
            continue
        src = re.search(r"\bsrc=[\"']([^\"']+)[\"']", tag, re.I)
        if src:
            out.append(_basename(src.group(1)))
    return out


def _foreground_srcs(section: str) -> list[str]:
    bg = set(_bg_srcs(section))
    return [src for src in _section_srcs(section) if src not in bg]


def _font_size_errors(section: str) -> list[str]:
    errors = []
    for raw in FONT_SIZE_RE.findall(section):
        size = float(raw)
        if size < 24:
            errors.append(f"发现过小字体 font-size:{raw}px；PPT 正文/图表标签必须使用统一字体 token 且不低于 24px")
    for raw in SVG_TEXT_SIZE_RE.findall(section):
        size = float(raw)
        if size < 24:
            errors.append(f"SVG 图表文字过小 font-size={raw}px；轴标/图例/节点标签必须使用可读字体 token")
    return errors


def _hex_to_rgb(color: str) -> tuple[int, int, int] | None:
    color = color.strip().lower()
    if color in {"black", "#000", "#000000"}:
        return (0, 0, 0)
    if color in {"white", "#fff", "#ffffff"}:
        return (255, 255, 255)
    if color.startswith("#"):
        raw = color[1:]
        if len(raw) == 3:
            raw = "".join(ch * 2 for ch in raw)
        if len(raw) == 6:
            try:
                return tuple(int(raw[i : i + 2], 16) for i in (0, 2, 4))  # type: ignore[return-value]
            except Exception:
                return None
    m = re.match(r"rgba?\(([^)]+)\)", color)
    if m:
        parts = [p.strip() for p in m.group(1).split(",")]
        if len(parts) >= 3:
            try:
                return (int(float(parts[0])), int(float(parts[1])), int(float(parts[2])))
            except Exception:
                return None
    return None


def _rel_lum(rgb: tuple[int, int, int]) -> float:
    def chan(v: int) -> float:
        x = v / 255.0
        return x / 12.92 if x <= 0.03928 else ((x + 0.055) / 1.055) ** 2.4

    r, g, b = (chan(v) for v in rgb)
    return 0.2126 * r + 0.7152 * g + 0.0722 * b


def _contrast_ratio(a: tuple[int, int, int], b: tuple[int, int, int]) -> float:
    l1 = _rel_lum(a)
    l2 = _rel_lum(b)
    hi, lo = max(l1, l2), min(l1, l2)
    return (hi + 0.05) / (lo + 0.05)


def _text_layout_errors(section: str) -> list[str]:
    errors: list[str] = []
    if WRITING_MODE_RE.search(section):
        errors.append("发现 vertical/sideways writing-mode；PPT 中文正文不得一字一行或竖排破碎")
    if GRID_NARROW_RE.search(section):
        errors.append("发现极窄 grid 列，容易导致中文一字一行；请改宽列或拆页")

    for tag in re.findall(r"<[^>]+style=[\"'][^\"']+[\"'][^>]*>[\s\S]{0,220}?</[^>]+>", section, re.I):
        style_m = STYLE_ATTR_RE.search(tag)
        if not style_m:
            continue
        style = style_m.group(1)
        text = _short_text(tag)
        if len(text) >= 8:
            widths = [float(v) for v in WIDTH_RE.findall(style)]
            if widths and min(widths) < 180:
                errors.append(f"文本框过窄({min(widths):.0f}px)导致中文易异常换行：{text[:24]}")

        color_m = TEXT_COLOR_RE.search(style)
        bg_m = BG_COLOR_RE.search(style)
        if color_m and bg_m and len(text) >= 2:
            fg = _hex_to_rgb(color_m.group(1))
            bg = _hex_to_rgb(bg_m.group(1))
            if fg and bg and _contrast_ratio(fg, bg) < 3.0:
                errors.append(f"文本与自身背景对比度不足：{text[:24]}")

    return errors


def _backplate_errors(section: str) -> list[str]:
    errors: list[str] = []
    for tag in re.findall(r"<[^>]+class=[\"'][^\"']+[\"'][^>]*>[\s\S]{0,500}?</[^>]+>", section, re.I):
        cls_m = CLASS_RE.search(tag)
        if not cls_m or not BACKPLATE_CLASS_RE.search(cls_m.group(1)):
            continue
        style_m = STYLE_ATTR_RE.search(tag)
        if not style_m:
            continue
        style = style_m.group(1)
        text = _short_text(tag)
        widths = [float(v) for v in WIDTH_RE.findall(style)]
        heights = [float(v) for v in HEIGHT_RE.findall(style)]
        too_wide = widths and max(widths) >= 760 and len(text) >= 18
        too_tall = heights and max(heights) >= 360 and len(text) >= 25
        if too_wide or too_tall:
            errors.append(
                f"文字背板/浮动层过大({cls_m.group(1)}），会遮挡图片并退回卡片化：{text[:28]}"
            )
    return errors


def _is_cutout_plan(item: dict | None) -> bool:
    if not isinstance(item, dict):
        return False
    return item.get("enhance_style") == "cutout" or item.get("image_role") == "foreground_cutout"


def _cutout_framed(section: str, src: str) -> bool:
    if not src:
        return False
    escaped = re.escape(src)
    # 只在图片附近检查，避免同页其它说明文字背板误伤透明前景特写。
    near = re.findall(rf"(<[^>]*?(?:{escaped})[^>]*>[\s\S]{{0,260}})", section, re.I)
    near += re.findall(rf"([\s\S]{{0,260}}<[^>]*?(?:{escaped})[^>]*>)", section, re.I)
    hay = "\n".join(near) if near else section if src in section else ""
    return bool(hay and BAD_FRAME_STYLE_RE.search(hay))


def _source_enhanced_framed(section: str, src: str) -> bool:
    """Detect white-card framing around the source image, not elsewhere on the page."""
    if not src:
        return False
    escaped = re.escape(src)
    img_tags = re.findall(rf"<img\b[^>]*{escaped}[^>]*>", section, re.I)
    if any(BAD_FRAME_STYLE_RE.search(tag) for tag in img_tags):
        return True

    # Check only likely immediate wrappers. Page-level text padding/borders are
    # normal and should not be treated as image framing.
    wrapper_pattern = (
        rf"<(?P<tag>figure|div)\b(?P<attrs>[^>]*)>"
        rf"(?:(?!</(?P=tag)>)[\s\S]){{0,520}}"
        rf"<img\b[^>]*{escaped}[^>]*>"
        rf"(?:(?!</(?P=tag)>)[\s\S]){{0,220}}</(?P=tag)>"
    )
    for match in re.finditer(wrapper_pattern, section, re.I):
        attrs = match.group("attrs") or ""
        cls_m = CLASS_RE.search(attrs)
        style_m = STYLE_ATTR_RE.search(attrs)
        classes = cls_m.group(1) if cls_m else ""
        style = style_m.group(1) if style_m else ""
        if BAD_FRAME_CLASS_RE.search(classes) and BAD_FRAME_STYLE_RE.search(style):
            return True
    return False


def _any_image_framed(section: str) -> bool:
    """Detect a likely image slot wrapped as a white card."""
    for src in _section_srcs(section):
        if _source_enhanced_framed(section, src):
            return True
    return False


def check_section(section: str, index: int, design: dict, deck_dir: Path, image_report: dict, source_plan: dict, strict: bool):
    section = SPEAKER_NOTES_RE.sub("", section)  # 讲稿不参与任何布局倾向/字数/资产扫描
    label_m = LABEL_RE.search(section)
    label = label_m.group(1) if label_m else f"{index:02d}"
    page_no = page_number(label, index)
    page_design = design.get(page_no, {})
    style = page_design.get("composition_style")
    grammar = page_design.get("page_grammar")
    errors: list[str] = []
    warnings: list[str] = []

    text = section_text(section)
    card_count = len(CARD_RE.findall(section))
    table_count = len(TABLE_RE.findall(section))
    has_bg = bool(BG_RE.search(section))
    img_count = len(re.findall(r"<img\b", section, re.I))
    bg_img_count = len(BG_IMG_RE.findall(section))
    foreground_img_count = max(0, img_count - bg_img_count)
    bg_srcs = _bg_srcs(section)
    fg_srcs = _foreground_srcs(section)
    all_srcs = _section_srcs(section)
    image_frame_count = len(IMAGE_FRAME_RE.findall(section))
    has_data_visual = bool(DATA_VISUAL_RE.search(section))
    has_strong_data_visual = bool(STRONG_DATA_VISUAL_RE.search(section))
    max_words = page_design.get("max_visible_words")
    supporting_visual = str(page_design.get("supporting_visual_layer") or "")
    contract = page_design.get("visual_asset_contract") if isinstance(page_design, dict) else None
    # 2026-07-06 真机误报：composition_style/page_grammar/supporting_visual_layer 都是自由文本，
    # 只能靠关键词/枚举值猜"这页该有图"；但 design.json 自己的 visual_asset_contract 才是权威——
    # foreground_asset/background_asset 显式声明为空串，就是设计阶段明确表态"这页前景/整页本就
    # 不打算配真实图片，用 HTML/SVG/文字代替"（如目录页 foreground_role="html_svg_marks"、章节页
    # 副标题浮前景本身就是纯文字层）。契约里显式声明的"无图"意图应优先于这些粗糙的文本猜测。
    contract_no_fg = isinstance(contract, dict) and not str(contract.get("foreground_asset") or "").strip()
    contract_no_image_at_all = contract_no_fg and not str(contract.get("background_asset") or "").strip()

    for src in _missing_assets(section, deck_dir):
        errors.append(f"引用的图片资产不存在: {src}")

    degraded = image_report.get("degraded", {})
    for src in all_srcs:
        if src in degraded:
            item = degraded[src]
            errors.append(
                f"引用的语义图片 {src} 来自生图降级 fallback={item.get('fallback') or 'unknown'}，"
                "不能作为最终产品详情页主视觉"
            )

    src_counts = Counter(all_srcs)
    bg_counts = Counter(bg_srcs)
    for src in sorted(bg_counts):
        if src_counts[src] > bg_counts[src]:
            hint = "；AI 前景必须独立规划为 ai_pN_fg.png" if AI_BACKGROUND_ONLY_RE.match(src) else ""
            errors.append(f"同一图片 {src} 在同页同时作为背景和前景，容易造成重复/切割/卡片化{hint}")

    for src in all_srcs:
        if src.startswith("enhanced_src_") and src not in source_plan.get("enhanced", {}):
            warnings.append(f"增强客户图 {src} 未在 source_layout_plan.json 中找到映射，建议检查来源关系")

    # ── 素材使用契约三连（2026-07-02 逐页体检裁决；plan 缺字段时不判，fail-open）──
    plan_images = source_plan.get("plan_images", {})
    for src in sorted(set(all_srcs)):
        item = plan_images.get(src)
        if not isinstance(item, dict):
            continue
        # ① 原图带字/需重绘禁令：规划标了 enhance_required（去字重绘版已生成/将生成），
        #    原图 src_N 绝不允许直接进 deck——坠机字幕图原样上墙（slide03 事故）就是这条失守。
        if item.get("enhance_required") or item.get("has_embedded_text"):
            enhanced_name = item.get("enhanced_file") or f"enhanced_{src}"
            errors.append(
                f"客户原图 {src} 规划为需重绘（enhance_required/图上带字），不得直接引用；"
                f"改引去字重绘版 {enhanced_name} 或删除该引用"
            )
        # ② 证据/嵌入图禁做整页背景：direct_contain/gallery/evidence 类（旧 PPT 截图、密信息图）
        #    只能 contain 框图展示，铺成背景再叠字 = slide22 事故。
        usage = str(item.get("usage_intent") or "")
        target_layer = str(item.get("target_layer") or "")
        if src in bg_srcs and (usage in {"direct_contain", "gallery", "discard"} or target_layer == "evidence"):
            errors.append(
                f"客户图 {src} 规划为 {usage or target_layer}（证据/嵌入类），不得用作整页背景；"
                "改为 contain 框图 + 短说明，且不得在其上覆盖正文"
            )
        # ③ 弃用图禁入 deck：规划判定与主题不相关/负面（如坠机资讯图）。
        if usage == "discard":
            errors.append(
                f"客户图 {src} 已被规划判定为弃用（与主题不相关/负面），不得出现在 deck 中；删除该引用"
            )

    # ④ 同族背景+前景重复：src_N 与 enhanced_src_N 视为同一主体（既有检查只抓同名同图）。
    #    背景已是该主体、前景再放同主体特写卡 = 重复抢戏（slide10/14 事故）。
    def _family(name: str) -> str:
        return re.sub(r"^enhanced_", "", name)

    bg_families = {_family(s) for s in bg_srcs}
    for src in sorted(set(fg_srcs)):
        fam = _family(src)
        if fam in bg_families and src not in bg_srcs:
            errors.append(
                f"客户图同族重复：背景已使用 {fam} 家族（src/enhanced），前景又放 {src}；"
                "保留一处主视觉，另一处删除或换独立互补素材"
            )

    if isinstance(contract, dict):
        foreground_role = str(contract.get("foreground_role") or "").strip().lower()
        foreground_asset = _asset_name(str(contract.get("foreground_asset") or ""))
        background_asset = _asset_name(str(contract.get("background_asset") or ""))
        if foreground_role in {"none", "无", "no", "null"} and fg_srcs:
            errors.append(
                f"design.visual_asset_contract 声明 foreground_role=none，但 HTML 仍插入前景图片 {fg_srcs[:3]}"
            )
        if background_asset and background_asset not in bg_srcs and background_asset in all_srcs:
            errors.append(f"契约要求 {background_asset} 是背景图，但 HTML 没有放入 bg-img/edit-bg 背景层")
        if foreground_asset and foreground_asset in bg_srcs:
            errors.append(f"契约要求 {foreground_asset} 是前景图，但 HTML 把它放入背景层")
        if background_asset and foreground_asset and background_asset == foreground_asset:
            errors.append("design.visual_asset_contract 背景和前景使用同一张图片")

    for src in fg_srcs:
        if AI_BACKGROUND_ONLY_RE.match(src):
            errors.append(f"{src} 是背景约定名，不能作为前景插图；前景 AI 必须独立规划为 ai_pN_fg.png")

    for src in fg_srcs:
        item = source_plan.get("enhanced", {}).get(src)
        if _is_cutout_plan(item):
            if src in bg_srcs:
                errors.append(f"cutout 客户图 {src} 被当背景使用；透明前景特写只能浮在独立背景上")
            if _cutout_framed(section, src):
                errors.append(f"cutout 客户图 {src} 被白底/边框/padding 包裹；应透明前景直接融入背景")

    errors.extend(_font_size_errors(section))
    errors.extend(_text_layout_errors(section))
    errors.extend(_backplate_errors(section))
    connector_scope = _strip_concentric_decorative_svgs(DECOR_SVG_RE.sub("", section))
    if (
        CONNECTOR_RE.search(connector_scope)
        and not DIAGRAM_NODE_RE.search(connector_scope)
        and not CHART_MARKER_RE.search(connector_scope)
        and not _has_labeled_shape_nodes(connector_scope)
    ):
        errors.append("发现孤立 line/path/polyline 连线，但没有 diagram-node/data-node/flow-step 等节点归属")

    if not has_bg:
        errors.append("缺少背景图层或背景引用")
    elif strict and not bg_srcs and style in IMAGE_LED_STYLES and not isinstance(contract, dict):
        # 2026-07-06 真机误报：design 常把真实图片契约声明在**前景**槽（background_role=
        # "vi_fallback" 故意留白背景、真实主视觉走 foreground_asset，如产品实物图/客户图放前景
        # 插图而非铺满整页背景），这条检查却只认 bg_srcs（背景层的图），把"图在前景不在背景"的
        # 合法设计判成"没有真实图片"。contract 存在时（不论声明有资产还是两槽都显式留空）都是
        # 设计阶段的明确表态，一律采信、不再用 bg_srcs 猜；只有 contract 整个缺失（旧版
        # design.json 没这个字段）才退回这条基于 bg_srcs 的粗糙检查。
        errors.append("影像叙事页没有真实背景图片，只靠 CSS 背景/渐变不足以成为产品详情页主视觉")
    if OBJECT_FILL_RE.search(section):
        errors.append("发现 object-fit:fill，图片可能被非等比拉伸")
    if _any_image_framed(section):
        errors.append("图片疑似被白底/边框/padding 裱成小卡，产品详情页式图槽应直接满铺")
    if strict:
        for src in [s for s in all_srcs if s.startswith("enhanced_src_")]:
            if _source_enhanced_framed(section, src):
                errors.append("source-enhanced 客户图被白底/边框/padding 包裹，不能作为产品详情页主视觉")
                break

    if grammar == "image-mosaic":
        if img_count < 3:
            errors.append("image-mosaic 至少需要 3 张图片作为主体")
            # 2026-07-06/07 两次真机复盘同一结论：这条"网格必须以图片为主体"检查此前跟 img_count
            # 门槛无关，只要 card_count>=3 且 card_count>img_count 就报——但两次生成的真实截图都是
            # "3 张真实驾驶舱照片图集 + 4-5 张解释每个痛点的文字卡片"，图集本身已充分满足"图片为
            # 主体"的证据要求，卡片是**独立的补充说明区**，不是把图片"换成"了文字卡片墙。只有真的
            # 没凑够 3 张图（第一条 img_count<3 已报）时，大量卡片才说明"图片被文字卡片顶替"，
            # 嵌套进这个分支后不再误伤"图集+说明"这种合理混合版式。
            if card_count >= 3 and img_count < card_count:
                errors.append("image-mosaic 的网格必须以图片为主体，不能是文字卡片网格")
        # 文字预算从 180 放宽到 280：两次真机复盘的"图集+说明"版式实测 201/242 字符，视觉效果良好，
        # 180 对这类合理混合版式过严；仍保留上限防止真正退化成纯文字墙。
        if len(text) > 280:
            errors.append(f"image-mosaic 文字过多: {len(text)} 字符，应只保留短标签")
    elif card_count >= 4 and style not in {"gallery-strip", "data-visual"}:
        errors.append(f"疑似卡片墙: card/panel 类出现 {card_count} 次")
    elif card_count >= 2 and style in IMAGE_LED_STYLES:
        errors.append(f"影像叙事页退回卡片/白卡分区: card/panel 类出现 {card_count} 次")
    if style in {"quote-focus", "chapter-cinematic"} and card_count:
        errors.append("quote-focus / chapter-cinematic 只能是大图大字和少量参数，不能出现卡片总结")

    if table_count and style != "data-visual" and grammar != "data-visual":
        errors.append("疑似表格/矩阵墙，但 composition_style 不是 data-visual")
    if (style == "data-visual" or grammar == "data-visual") and not has_strong_data_visual:
        errors.append("data-visual 页必须包含 SVG/chart/axis/bar/line 等可编辑图形化表达，不能只放表格或文字")
    if (style == "data-visual" or grammar == "data-visual") and card_count >= 3 and not has_strong_data_visual:
        errors.append("data-visual 页不能用多张文字卡片替代真正的图表/参数轴")
    if len(text) > 260 and style not in {"data-visual", "gallery-strip"}:
        warnings.append(f"文字量偏高: {len(text)} 字符，建议图形化或拆页")
    # 知情反转（2026-07-02 逐页体检）：字数预算从 ERROR(×2) 降为 WARNING(×3)——预算是设计期 LLM 拍的
    # 紧值（50-80），把时间轴标签/图内短标全算进去，视觉良好页（06 四失/20 风险）反被判「文字墙」。
    # 文字过多的**后果**（越界/重叠/挤压）由几何门按坐标精确抓，字数只作精炼提示。
    if isinstance(max_words, int) and len(text) > max_words * 3 and style not in {"gallery-strip"}:
        warnings.append(f"实际文字量 {len(text)} 明显超过设计预算 max_visible_words={max_words}，建议精炼/图形化")
    if img_count == 0 and style in {"product-hero", "feature-theater", "detail-closeup", "scenario-fullbleed"} and not contract_no_image_at_all:
        errors.append(f"{style} 需要图片/场景主视觉，但页面没有 img")
    if strict and style in IMAGE_LED_STYLES and not (bg_srcs or fg_srcs) and not contract_no_image_at_all:
        errors.append(f"{style} 必须有真实 AI/客户图主视觉，不能只用渐变、色块或卡片补救")
    if grammar in {"hero-scene", "cinematic-feature", "product-closeup", "before-after-scene", "spec-overlay"} and img_count == 0 and not contract_no_image_at_all:
        errors.append(f"{grammar} 需要产品/场景/特写主视觉，但页面没有 img")
    if grammar in {"hero-scene", "cinematic-feature", "product-closeup", "spec-overlay"} and image_frame_count == 0:
        warnings.append(f"{grammar} 建议使用 fig-fill/product-visual/closeup 等明确图槽类，便于检查图像主导")
    if grammar == "before-after-scene" and card_count >= 2:
        errors.append("before-after-scene 应使用左右大图/大场景对比，不能用 before/after 卡片组")
    if (re.search(r"底部|前景|特写|插图|场景|锚点|产品", supporting_visual) and foreground_img_count == 0
            and not has_strong_data_visual and not contract_no_fg):
        errors.append("design 要求辅助视觉层，但 HTML 只有背景/文字，没有前景插图、特写或数据视觉")
    if not style:
        errors.append("design.json 缺少 composition_style，无法验证构图落地")
    if not grammar:
        errors.append("design.json 缺少 page_grammar，无法验证 Apple/DJI 式页面语法")

    return label, errors, warnings


# 2026-07-06 真机复盘：`.deck-title on-dark`/`.deck-subtitle on-dark` 这类组合在深色背景页（scrim-top-dark
# 等）里标题/副标题实际渲染成深墨字直接压在照片上，肉眼截图确认几乎不可读。根因是样式表里只给
# `.t-eyebrow`/`.t-takeaway`/`.t-subtitle`/`.t-body`/`.chip`/`.metric-num`/`.metric-label` 定义了
# `.on-dark`/`.on-light` 修饰符组合，但 HTML 用了 `class="deck-title on-dark"`，样式表压根没有
# `.deck-title.on-dark` 这条规则——修饰符对这个元素零效果，不是"被更高特异性覆盖"（那是另一种已知
# 模式），是"这个组合从未被定义过"。跟改哪个具体组件名字无关，是"on-dark/on-light 工具类只对部分
# 组件类实现、忘了其余实际用到的组件类"这一类通用缺口，用确定性扫描全量捕获比逐条记文案更可靠。
ON_DARK_LIGHT_MODIFIER_RE = re.compile(r"^(?:on-dark|on-light)$")
COMPOUND_MODIFIER_SELECTOR_RE = re.compile(r"\.([A-Za-z][\w-]*)\.(on-dark|on-light)\b")
CLASS_ATTR_RE = re.compile(r"class=[\"']([^\"']+)[\"']", re.I)
STYLE_BLOCK_RE = re.compile(r"<style\b[^>]*>[\s\S]*?</style>", re.I)


def _check_on_dark_light_gaps(html: str) -> list[str]:
    style_m = re.search(r"<style\b[^>]*>([\s\S]*?)</style>", html, re.I)
    if not style_m:
        return []
    defined = {(m.group(1), m.group(2)) for m in COMPOUND_MODIFIER_SELECTOR_RE.finditer(style_m.group(1))}
    if not defined:
        return []  # 这份 deck 没用 on-dark/on-light 工具类约定，fail-open 不判
    body = SPEAKER_NOTES_RE.sub("", STYLE_BLOCK_RE.sub("", html))
    errors: list[str] = []
    seen: set[tuple] = set()
    for m in CLASS_ATTR_RE.finditer(body):
        classes = m.group(1).split()
        modifiers = [c for c in classes if ON_DARK_LIGHT_MODIFIER_RE.match(c)]
        if not modifiers:
            continue
        bases = [c for c in classes if not ON_DARK_LIGHT_MODIFIER_RE.match(c)]
        if not bases:
            continue
        for modifier in modifiers:
            if any((b, modifier) in defined for b in bases):
                continue
            key = (tuple(sorted(bases)), modifier)
            if key in seen:
                continue
            seen.add(key)
            errors.append(
                f"class=\"{' '.join(classes)}\" 用了 {modifier} 修饰符，但样式表没有为 "
                f"{'/'.join(bases)} 定义对应的 .{bases[0]}.{modifier} 规则——这个修饰符对它零效果，"
                f"实际颜色仍是该类的默认色（深底深字/浅底浅字风险）；补一条 .{bases[0]}.{modifier} 规则，"
                "或改用内联 style 显式定色"
            )
    return errors


def main(argv=None):
    parser = argparse.ArgumentParser()
    parser.add_argument("deck", help="build/deck.html")
    parser.add_argument("--design", help="build/design.json")
    parser.add_argument("--image-report", help="build/image_generation_report.json")
    parser.add_argument("--source-plan", help="build/source_layout_plan.json")
    parser.add_argument("--strict-product-detail", action="store_true", help="启用 Apple/DJI 产品详情页式硬门")
    parser.add_argument("-v", "--verbose", action="store_true")
    args = parser.parse_args(argv)

    try:
        html = Path(args.deck).read_text(encoding="utf-8", errors="ignore")
    except Exception as exc:  # noqa: BLE001
        print(f"DECK_VISUAL_STYLE_FAILED: {exc}")
        return 2

    sections = SECTION_RE.findall(html)
    if not sections:
        print("DECK_VISUAL_STYLE_FAILED: 未找到 section.slide")
        return 2

    design = load_design(args.design)
    image_report = load_image_report(args.image_report)
    source_plan = load_source_plan(args.source_plan)
    all_errors: list[str] = []
    all_warnings: list[str] = []
    for idx, section in enumerate(sections, 1):
        label, errors, warnings = check_section(
            section,
            idx,
            design,
            Path(args.deck).parent,
            image_report,
            source_plan,
            args.strict_product_detail,
        )
        all_errors.extend(f"{label}: {e}" for e in errors)
        all_warnings.extend(f"{label}: {w}" for w in warnings)

    all_errors.extend(f"全局样式表: {e}" for e in _check_on_dark_light_gaps(html))

    # 系统性同字号归组（2026-07-05 真机复盘：单份 deck 里 10 处 ERROR 共享同一个错误字号 font-size:22px，
    # 分散在 3 个不同页面/不同组件——跟 text_readability_pixel.py 已验证过的「系统性同色归组」同一根因：
    # 逐条改在有限修复轮数内修不完，真正的修法是一次性把这个错误数值批量替换成 ≥24px。纯汇总已收集的
    # errors、不新增判断，只是把「这些其实是一件事」的信号显式标出来）。
    font_size_counts = Counter(
        m.group(1) for e in all_errors for m in [re.search(r"font-size[:=]\"?'?(\d+(?:\.\d+)?)", e)] if m
    )
    for size, count in font_size_counts.most_common():
        if count >= SYSTEMIC_FONT_SIZE_MIN_COUNT:
            all_errors.append(
                f"⚠️ {count} 处过小字体共享同一数值 font-size:{size}px：疑似同一错误字号被多处复用/独立重复选中，"
                f"建议一次性全文搜索替换该数值到 ≥24px（或改用共享字体 token），而非逐条改——"
                f"逐条修在有限轮数内修不完，改一次能同时清零全部同数值实例。"
            )

    for item in all_errors:
        print(f"ERROR: {item}")
    if args.verbose:
        for item in all_warnings:
            print(f"WARNING: {item}")

    if all_errors:
        print(f"DECK_VISUAL_STYLE_FAILED: {len(all_errors)} 个阻断问题")
        return 1
    print(f"DECK_VISUAL_STYLE_OK: {len(sections)} 页")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
