#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""检查 PPT design.json 是否真正进入产品详情页式构图。

这个脚本只做确定性护栏：字段缺失、风格枚举非法、卡片/表格作为默认表达等会报 ERROR。
它不评判审美好坏，但会阻止弱模型退回「archetype + 卡片墙」旧路径。

视觉优先内容形状（2026-07-02，治「文本阅读型页面」）
====================================================
参考 visual-first 标准：一页一个想法、上屏文字 3–5 秒读完、短语不成段、
论证细节进 speaker_notes（讲稿）或拆页。三条确定性检查：
① max_visible_words 对账（ERROR）——页面自己声明了上屏字数预算却从无人核对，
   takeaway+points 实际字数超声明×1.2 即违约（标题另由 design_budget_check 管长度）；
② 影像叙事页内容形状（ERROR）——hero-scene 等「图是主角」页，points 只许 ≤3 条短语（≤20 字）；
③ 文章化倾向（WARNING，保守防把对的改错）——≥4 条要点且平均 >18 字 = 文本阅读型排布。
`speaker_notes` 是可选讲稿字段（论证/机制/出处放这里，导出进 PPT 备注栏），
**不计入上屏字数、不参与卡片/表格倾向文本扫描**。
"""

from __future__ import annotations

import argparse
import json
import re
import sys
from pathlib import Path


ALLOWED_STYLES = {
    "product-hero",
    "feature-theater",
    "detail-closeup",
    "scenario-fullbleed",
    "data-visual",
    "gallery-strip",
    "chapter-cinematic",
    "quote-focus",
}
ALLOWED_PAGE_GRAMMARS = {
    "hero-scene",
    "cinematic-feature",
    "product-closeup",
    "image-mosaic",
    "spec-overlay",
    "data-visual",
    "before-after-scene",
}
TEXT_ZONES = {"left", "right", "top", "bottom", "center"}
TEXT_OVERLAY_MODES = {"scrim", "floating-text", "frosted-caption", "side-copy", "none"}
PRIMARY_VISUAL_TYPES = {
    "ai-background",
    "foreground-ai",
    "source-enhanced-background",
    "source-enhanced-hero",
    "transparent-closeup",
    "scene-photo",
    "product-render",
    "html-svg-chart",
    "image-mosaic",
}
REQUIRED_FIELDS = {
    "one_sentence_takeaway",
    "composition_style",
    "visual_focus",
    "text_zone",
    "visual_role",
    "copy_budget",
    "page_grammar",
    "image_weight",
    "text_overlay_mode",
    "primary_visual_type",
    "safe_text_zone",
    "max_visible_words",
    "main_visual_layer",
    "supporting_visual_layer",
    "text_overlay_zone",
    "visual_story",
    "semantic_image_prompt",
    "forbidden_layout",
    "visual_asset_contract",
}
TEXT_FOCUS_RE = re.compile(r"文字|文案|内容|要点|标题|段落|copy|text", re.I)
CARD_RE = re.compile(r"卡片墙|悬浮卡|网格|四卡|五卡|六卡|card|cards|panel", re.I)
TABLE_RE = re.compile(r"表格|矩阵|table|matrix", re.I)
NO_TEXT_RE = re.compile(r"no\s+(?:text|words|letters|logo|logos)|不要.*(?:文字|字母|logo|水印)", re.I)
HTML_SVG_RE = re.compile(r"^html-svg|HTML/SVG|svg|图表|柱状|折线|参数轴|坐标轴|流程|架构|关系|时间线|bar|line|axis|chart", re.I)
GENERIC_BG_RE = re.compile(r"^(?:vi)?(?:同色系)?(?:抽象)?(?:渐变|纹理|背景|氛围|色块|底图)$", re.I)
BACKGROUND_TEXT_MARKER_RE = re.compile(
    r"(?:章节|序号|编号|号码|数字|标号|标签|题注|文字|文案|1\s*/\s*2\s*/\s*3\s*/\s*4|"
    r"\b(?:number|numbers|numbered|chapter|chapters|label|labels|caption|captions|text|words|letters)\b)",
    re.I,
)
IMAGE_LED_STYLES = {
    "product-hero",
    "feature-theater",
    "detail-closeup",
    "scenario-fullbleed",
    "chapter-cinematic",
    "quote-focus",
}
AI_VISUAL_TYPES = {
    "ai-background",
    "foreground-ai",
    "source-enhanced-background",
    "source-enhanced-hero",
    "transparent-closeup",
    "scene-photo",
    "product-render",
    "image-mosaic",
}
# 「图是主角」的影像叙事页语法：文字只许少量短语浮净区（视觉优先内容形状检查 ②）。
IMAGE_NARRATIVE_GRAMMARS = {"hero-scene", "cinematic-feature", "product-closeup", "before-after-scene"}
VISIBLE_WORDS_FACTOR = 1.2       # 对账余量：takeaway+points 超声明 max_visible_words×此系数才报
NARRATIVE_MAX_POINTS = 3         # 影像叙事页 points 条数硬顶
NARRATIVE_MAX_POINT_LEN = 20     # 影像叙事页单条短语字数硬顶
PROSE_MIN_POINTS = 4             # 文章化倾向：至少这么多条
PROSE_AVG_LEN = 18               # 且平均字长超此 → 文本阅读型排布 WARNING


def points_texts(page: dict) -> list[str]:
    """归一化上屏要点文本：优先 points，缺则回退 blocks 的 content（与 design_budget_check 同口径）。"""
    def _texts(v) -> list[str]:
        out: list[str] = []
        if not isinstance(v, list):
            return out
        for x in v:
            if isinstance(x, str):
                out.append(x)
            elif isinstance(x, (int, float)):
                out.append(str(x))
            elif isinstance(x, dict):
                c = x.get("content") or x.get("text") or ""
                if isinstance(c, str):
                    out.append(c)
        return out

    pts = _texts(page.get("points"))
    return pts if pts else _texts(page.get("blocks"))


def load_pages(path: Path):
    with path.open(encoding="utf-8-sig") as f:
        data = json.load(f)
    pages = data.get("pages") if isinstance(data, dict) else None
    if not isinstance(pages, list):
        raise ValueError("design.json 必须是包含 pages 数组的对象")
    return pages


def text_of(value) -> str:
    if value is None:
        return ""
    if isinstance(value, str):
        return value
    if isinstance(value, (int, float, bool)):
        return str(value)
    if isinstance(value, list):
        return " ".join(text_of(v) for v in value)
    if isinstance(value, dict):
        return " ".join(text_of(v) for v in value.values())
    return str(value)


def check_page(page: dict, index: int):
    label = page.get("page", index)
    errors: list[str] = []
    warnings: list[str] = []

    missing = sorted(k for k in REQUIRED_FIELDS if k not in page)
    if missing:
        errors.append(f"缺少产品详情页式硬字段: {', '.join(missing)}")

    style = page.get("composition_style")
    if style is not None and style not in ALLOWED_STYLES:
        errors.append(f"composition_style 非法: {style!r}")

    grammar = page.get("page_grammar")
    if grammar is not None and grammar not in ALLOWED_PAGE_GRAMMARS:
        errors.append(f"page_grammar 非法: {grammar!r}")

    zone = page.get("text_zone")
    if zone is not None and zone not in TEXT_ZONES:
        errors.append(f"text_zone 非法: {zone!r}")
    safe_zone = page.get("safe_text_zone")
    if safe_zone is not None and safe_zone not in TEXT_ZONES:
        errors.append(f"safe_text_zone 非法: {safe_zone!r}")

    overlay = page.get("text_overlay_mode")
    if overlay is not None and overlay not in TEXT_OVERLAY_MODES:
        errors.append(f"text_overlay_mode 非法: {overlay!r}")

    visual_type = page.get("primary_visual_type")
    if visual_type is not None and visual_type not in PRIMARY_VISUAL_TYPES:
        errors.append(f"primary_visual_type 非法: {visual_type!r}")

    contract = page.get("visual_asset_contract")
    if "visual_asset_contract" in page:
        if not isinstance(contract, dict):
            errors.append("visual_asset_contract 必须是对象，声明背景/前景图片角色契约")
        else:
            for key in ("background_role", "foreground_role"):
                if not str(contract.get(key) or "").strip():
                    errors.append(f"visual_asset_contract 缺少 {key}")
            bg_asset = str(contract.get("background_asset") or "").strip()
            fg_asset = str(contract.get("foreground_asset") or "").strip()
            if bg_asset and fg_asset and bg_asset == fg_asset:
                errors.append("visual_asset_contract 背景和前景不能使用同一张图片")
            if fg_asset and re.fullmatch(r"ai_p\d+\.(?:png|jpg|jpeg|webp)", fg_asset, re.I):
                errors.append("前景 AI 插图不能使用 ai_pN.png；必须独立规划 ai_pN_fg.png")

    main_visual = str(page.get("main_visual_layer") or "").strip()
    supporting_visual = str(page.get("supporting_visual_layer") or "").strip()
    text_overlay_zone = page.get("text_overlay_zone")
    semantic_prompt = str(page.get("semantic_image_prompt") or "").strip()
    forbidden_layout = page.get("forbidden_layout")

    if main_visual:
        if TEXT_FOCUS_RE.search(main_visual):
            errors.append(f"main_visual_layer 不能是文字/内容本身: {main_visual}")
        if GENERIC_BG_RE.fullmatch(main_visual):
            errors.append(f"main_visual_layer 不能只是抽象渐变/纹理: {main_visual}")

    if text_overlay_zone is not None and not isinstance(text_overlay_zone, str):
        errors.append("text_overlay_zone 必须是字符串，说明文字净区位置")
    elif isinstance(text_overlay_zone, str) and not text_overlay_zone.strip():
        errors.append("text_overlay_zone 不能为空")

    if "semantic_image_prompt" in page and not semantic_prompt:
        errors.append("semantic_image_prompt 不能为空")
    if semantic_prompt:
        is_html_svg_prompt = bool(HTML_SVG_RE.search(semantic_prompt))
        if visual_type in AI_VISUAL_TYPES or (isinstance(page.get("visual"), dict) and str(page["visual"].get("route", "")).lower() in {"ai-a", "ai-b", "source-enhanced"}):
            if is_html_svg_prompt:
                errors.append("AI/图生图页面的 semantic_image_prompt 不能写成 html-svg，应是真实画面提示词")
            if not NO_TEXT_RE.search(semantic_prompt):
                errors.append("AI/图生图提示词必须明确 no text / no logo / no letters，避免图片里烧字")
            bg_role = ""
            if isinstance(contract, dict):
                bg_role = str(contract.get("background_role") or "")
            marker_source = " ".join(
                str(page.get(k) or "")
                for k in ("visual_focus", "visual_story", "main_visual_layer")
            )
            if ("background" in bg_role.lower() or visual_type == "ai-background") and BACKGROUND_TEXT_MARKER_RE.search(marker_source):
                errors.append("AI 背景/场景图不得要求生成章节序号、编号、标签或文字；这些必须放到 HTML/SVG 可编辑前景层")
        if visual_type == "html-svg-chart" or grammar == "data-visual":
            if not is_html_svg_prompt:
                errors.append("data-visual / html-svg-chart 页的 semantic_image_prompt 必须声明 html-svg 图表类型")

    if "forbidden_layout" in page:
        if not isinstance(forbidden_layout, list) or not forbidden_layout:
            errors.append("forbidden_layout 必须是非空数组")
        else:
            joined = " ".join(str(x) for x in forbidden_layout)
            if "card" not in joined.lower() and "卡" not in joined:
                errors.append("forbidden_layout 必须显式禁止 card wall / 卡片墙")
            if "table" not in joined.lower() and "表" not in joined:
                errors.append("forbidden_layout 必须显式禁止 table wall / 表格墙")

    image_weight = page.get("image_weight")
    if "image_weight" in page:
        if not isinstance(image_weight, (int, float)):
            errors.append("image_weight 必须是 0.0-1.0 数字")
        elif not 0 <= float(image_weight) <= 1:
            errors.append(f"image_weight 越界: {image_weight!r}")

    max_words = page.get("max_visible_words")
    if "max_visible_words" in page:
        if not isinstance(max_words, int):
            errors.append("max_visible_words 必须是整数")
        elif max_words > 80 and grammar not in {"data-visual", "image-mosaic"}:
            errors.append("max_visible_words 过高，产品详情页式页面不应承载长文")

    focus = str(page.get("visual_focus") or "").strip()
    if focus and TEXT_FOCUS_RE.search(focus):
        errors.append(f"visual_focus 不能是文字/内容本身: {focus}")

    if style in IMAGE_LED_STYLES and semantic_prompt and HTML_SVG_RE.search(semantic_prompt):
        errors.append(f"{style} 是影像叙事页，semantic_image_prompt 不应退成 HTML/SVG 图表")
    if style == "quote-focus" and (not supporting_visual or supporting_visual.lower() in {"none", "无"}):
        errors.append("quote-focus 也需要底部场景锚点、氛围背景或前景特写，不能只有文字")
    if grammar == "before-after-scene" and zone == "bottom" and ("左" in focus and "右" in focus):
        errors.append("before-after-scene 的左右对比画面不应把主文字净区放在 bottom，容易回到上下卡片化")

    budget = page.get("copy_budget")
    if "copy_budget" in page and not isinstance(budget, dict):
        errors.append("copy_budget 必须是对象")
    elif isinstance(budget, dict):
        for key in ("title_max", "takeaway_max", "point_max", "note_max"):
            if key not in budget:
                errors.append(f"copy_budget 缺少 {key}")

    archetype = str(page.get("archetype") or "")
    scan_page = dict(page)
    # forbidden_layout 里故意会写 no card wall / no table wall，不能反过来当作页面正在使用卡片/表格。
    scan_page.pop("forbidden_layout", None)
    # speaker_notes 是讲稿（论证/机制细节），提到「表格/矩阵/对比」是在讲内容、不是页面布局倾向。
    scan_page.pop("speaker_notes", None)
    all_text = text_of(scan_page)
    if archetype == "cards" and style != "gallery-strip":
        errors.append("cards archetype 只能用于 gallery-strip 或少量证据画廊，不得作为普通正文页默认")
    if CARD_RE.search(all_text) and grammar != "image-mosaic" and style not in {"gallery-strip", "data-visual"}:
        errors.append("页面仍含卡片墙/网格/悬浮卡倾向，但 composition_style 不是 gallery-strip/data-visual")
    if TABLE_RE.search(all_text) and style != "data-visual" and grammar != "data-visual":
        errors.append("页面仍含表格/矩阵倾向，但 composition_style 不是 data-visual")

    if grammar == "image-mosaic":
        if isinstance(max_words, int) and max_words > 55:
            errors.append("image-mosaic 只能是影像拼贴 + 短标签，max_visible_words 不应超过 55")
        if isinstance(image_weight, (int, float)) and float(image_weight) < 0.65:
            errors.append("image-mosaic 的图片视觉重量必须至少 0.65")
    elif grammar in {"hero-scene", "cinematic-feature", "product-closeup", "before-after-scene"}:
        if isinstance(image_weight, (int, float)) and float(image_weight) < 0.60:
            errors.append(f"{grammar} 的图片/场景视觉重量必须至少 0.60")
    elif grammar == "spec-overlay":
        if visual_type == "html-svg-chart":
            warnings.append("spec-overlay 应以产品/场景图为主，参数只作叠层；若图表主导请改 data-visual")

    points = page.get("points")
    if isinstance(points, list) and len(points) > 5 and style not in {"data-visual", "gallery-strip"} and grammar not in {"data-visual", "image-mosaic"}:
        warnings.append("points 超过 5 条，建议拆页或改成 data-visual")

    # ── 视觉优先内容形状（治「文本阅读型页面」：屏上=短语/数字/图，论证进 speaker_notes/拆页）──
    point_list = points_texts(page)
    takeaway = str(page.get("one_sentence_takeaway") or "")
    # ① max_visible_words 对账：页面自声明的上屏字数预算 vs takeaway+points 实际字数
    #   （标题长度另由 design_budget_check 管，不重复计入；1.2 余量防误伤贴线页）。
    if isinstance(max_words, int) and max_words > 0:
        visible = len(takeaway.strip()) + sum(len(str(p).strip()) for p in point_list)
        visible_cap = int(max_words * VISIBLE_WORDS_FACTOR)
        if visible > visible_cap:
            errors.append(
                f"上屏文案 {visible} 字超自声明 max_visible_words={max_words}（含余量上限 {visible_cap}）"
                "：points 短语化 / 论证移入 speaker_notes / 拆页——观众 3–5 秒要能读完一页"
            )
    # ② 影像叙事页内容形状：图是主角，文字只许 ≤3 条短语（≤20 字）浮净区
    if grammar in IMAGE_NARRATIVE_GRAMMARS and point_list:
        longest = max(len(str(p).strip()) for p in point_list)
        if len(point_list) > NARRATIVE_MAX_POINTS or longest > NARRATIVE_MAX_POINT_LEN:
            errors.append(
                f"{grammar} 影像叙事页文字超载（{len(point_list)} 条 / 最长 {longest} 字）"
                f"：points ≤{NARRATIVE_MAX_POINTS} 条且每条 ≤{NARRATIVE_MAX_POINT_LEN} 字短语；"
                "完整论证进 speaker_notes 或拆页"
            )
    # ③ 文章化倾向（保守 WARNING）：多条长句 = 文本阅读型排布
    if len(point_list) >= PROSE_MIN_POINTS:
        avg_len = sum(len(str(p).strip()) for p in point_list) / len(point_list)
        if avg_len > PROSE_AVG_LEN:
            warnings.append(
                f"文本阅读型排布倾向（{len(point_list)} 条要点平均 {avg_len:.0f} 字）"
                "：改短语/数字标签、把论述交给图表或 speaker_notes"
            )

    title = str(page.get("title") or "")
    if len(title) > 18 and style not in {"chapter-cinematic", "quote-focus"}:
        warnings.append("标题偏长，可能破坏产品详情页式一眼重点")

    return label, errors, warnings


def main(argv=None):
    parser = argparse.ArgumentParser()
    parser.add_argument("design", help="build/design.json")
    parser.add_argument("-v", "--verbose", action="store_true")
    args = parser.parse_args(argv)

    try:
        pages = load_pages(Path(args.design))
    except Exception as exc:  # noqa: BLE001
        print(f"DESIGN_STYLE_FAILED: {exc}")
        return 2

    all_errors: list[str] = []
    all_warnings: list[str] = []
    for idx, page in enumerate(pages, 1):
        if not isinstance(page, dict):
            all_errors.append(f"第{idx}页: page 必须是对象")
            continue
        label, errors, warnings = check_page(page, idx)
        all_errors.extend(f"第{label}页: {e}" for e in errors)
        all_warnings.extend(f"第{label}页: {w}" for w in warnings)

    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"DESIGN_STYLE_FAILED: {len(all_errors)} 个阻断问题")
        return 1
    print(f"DESIGN_STYLE_OK: {len(pages)} 页")
    return 0


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