#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
plan_source_layout.py —— 客户图「版式 + 图生图增强」**确定性**规划器（ppt 工作流专用）。

为什么需要（根因治理）
======================
规则、能力、数据、闸门都齐了，客户图却仍被用烂（低清原图硬铺当背景、满屏文字配角落小图、
该图生图增强的没增强）：根因是「每张图 → 用什么版式 / 要不要图生图 / 文字排哪 / 配什么色 / 用什么
提示词」这一**逐图决策**全压在一个弱模型身上——它要边读上百行 prose、边对十几页逐张心算分辨率
是否过线、边兼顾其它十几条要求，必然走「省事路径」（直接铺、堆文字），而非「正确但费事路径」
（route=source-enhanced + 图生图）。

本脚本把**可计算的那部分**从弱模型手里收成确定性算法：读 material.json（每图 base + vision 识图 +
stats 统计），为每张客户图算出 quality / usage_intent / 是否必须图生图 / 目标比例 / 推荐图文混排模板 /
文字落区 / 文字深浅，并**直接生成图生图提示词骨架**（英文、只表达「增强变换」，主体由 --input-image
参考图携带，无需翻译中文识图）。设计步从此「按算好的约束选模板」，不再自由心算。

阈值与「低清不得做背景」判定**复用 source_usage_check.py 的单一真相源**（LOW_RES_BG_MIN_WIDTH /
LOW_RES_BG_MIN_MEGAPIXELS / _is_low_res_for_background），避免两处阈值漂移。

模板名对齐 ui-design 既有 references（layout-composition.md §2.1/§2.2 + source-image-layout.md），
不另造名词——脚本只做「确定性映射」，模板定义仍是 references 单一来源。

两个模式
========
1. 规划（默认）：`python plan_source_layout.py [--build ./build]`
   读 build/material.json → 写 build/source_layout_plan.json（机读）+ build/source_layout_plan.md（人/LLM 读）。
   恒成功（无 material/无客户图也写空规划）；只用标准库 + 同目录 source_usage_check。

2. 兜底注入（reconcile）：`python plan_source_layout.py --ensure-img-plan [--build ./build]`
   读 source_layout_plan.json 的 enhance_entries，**union 进 build/img_plan.json**（按 file 去重），
   保证「必须图生图」的客户图一定有 image-to-image 生图条目——**不靠设计 LLM 记得加**。置于生图前调用。

退出码：0（恒成功路径）。
"""

import argparse
import json
import os
import re
import shutil
import sys

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import source_usage_check as su  # noqa: E402  复用低清阈值与判定（单一真相源）


# 极端比例：窄到 <0.45 或宽到 >3.6 的原图，塞进标准槽位必大留黑边或重裁 → 需图生图改比例。
BAD_ASPECT_MIN = 0.45
BAD_ASPECT_MAX = 3.6
# 文字深浅分界：图（或叠字区）平均亮度 ≥ 此值算「亮底」→ 深墨字；否则「暗底」→ 白字。
BRIGHTNESS_DARK_TEXT_MIN = 140
# 同章节图片数 ≥ 此值视为「可组画廊」。
GALLERY_MIN_PER_SECTION = 3

# 客户图「显示档位 → 最小占画布比例」（治「图被缩成角落小图/底部小条看不清」）：
# 任何客户图显示都不得低于其档位下限；够大/高清的图给大槽（背景/hero），别塞进小卡缩成看不清。
MIN_CANVAS_FRACTION = {
    "discard": 0.0,           # 弃用图（不相关/负面）：不进 deck、无槽位
    "background": 1.0,        # 整页底图
    "foreground_hero": 0.30,  # 前景主视觉 / 半幅大图（≈半背景），至少占画布 ~30%
    "evidence_card": 0.12,    # 证据图也必须可读，绝非角落缩略图
    "gallery": 0.10,          # 画廊每格下限
}
# 栅格客户图缩放上限（用户原话「最多 1 倍」）：原图**绝不放大超过原生像素**（放大=糊）。
# 要显示得比原生大 → 必须图生图重绘到目标分辨率（enhance），不是硬拉伸 object-fit。
MAX_UPSCALE = 1.0

# 「信息密集图」关键词（截图/图表/界面/结构图等）。
# ⚠️ 用户明确要求：这类**照样 img2img 重绘**（enhance_style="dense"），但用「忠实保留版面与数据结构、
# 清晰化、去杂、统一 PPT 风格」的提示词。**数据图 img2img 天然有重绘/篡改风险，best-effort**——不背景化、
# 保持原始框幅；usage_intent 仍是 direct_contain（图文混排、不堆卡墙），与「全图生图」政策一致。
DENSE_INFO_KEYWORDS = (
    "截图", "屏幕", "界面", "仪表盘", "控制台", "图表", "表格", "柱状", "折线", "饼图",
    "曲线图", "流程", "架构", "示意图", "结构图", "矩阵", "参数表", "列表", "网页", "网站",
    "文档", "表单", "代码", "对比图", "时间线", "看板",
    "screenshot", "dashboard", "chart", "graph", "table", "diagram", "flowchart",
    "ui", "interface", "matrix", "spreadsheet", "plot", "console",
)

_NO_TEXT_TAIL = "no text, no words, no letters, no captions, no logos"

# ③ 统一质量/分辨率词（用户要求：样式/质量/高分辨率写进每态提示词）。bg 另加 cinematic depth、cutout 另加 crisp cut-out edges。
_QUALITY = "photorealistic, sharp focus, high resolution (2K), clean professional lighting, high detail. "

# ② 背景类型关键词（识图驱动图生图分流，见 _background_kind）：
#   real_scene = 真实场景/环境/全景 → 保留并增强场景（hero，不去背景）；
#   flat_base  = 纯色/渐变/白底/棚拍底/纹理 → 离散主体抠透明 或 换 VI 同色系干净底；
#   皆不命中 → unknown（回落既有 usage_intent + 离散主体启发式）。
# real_scene 优先于 flat_base（真实场景误判代价高——宁可保场景也别误抠/误换底）。
REAL_SCENE_KEYWORDS = (
    "现场", "车间", "厂房", "环境", "全景", "驾驶舱", "户外", "天空", "场景",
    "工厂", "产线", "生产线", "机房", "鸟瞰", "航拍", "实景", "街景", "园区",
    "scene", "on-site", "on site", "factory", "workshop", "outdoor", "panorama",
    "environment", "cockpit", "real scene", "on location",
)
FLAT_BASE_KEYWORDS = (
    "白底", "纯色背景", "纯色底", "纯色", "单色背景", "灰底", "黑底", "渐变", "棚拍",
    "抠图", "纹理底", "白色背景", "无背景",
    "studio", "gradient", "plain background", "solid color", "solid background",
    "white background", "seamless backdrop", "product shot on white",
)


def _background_kind(vision):
    """识图驱动的背景类型分流：'real_scene' / 'flat_base' / 'unknown'。
    取 vision 的 description + palette_impression + key_elements 关键词判定；real_scene 优先命中（保守保场景）。
    驱动 _enhance_prompt 的 bg/hero/cutout 三态选择（与 _is_discrete_subject 联动，见 plan_one::enhance_style）。"""
    if not isinstance(vision, dict):
        return "unknown"
    hay = " ".join(
        [str(vision.get("description") or ""), str(vision.get("palette_impression") or "")]
        + [str(x) for x in (vision.get("key_elements") or []) if isinstance(x, (str, int, float))]
    ).lower()
    if any(kw.lower() in hay for kw in REAL_SCENE_KEYWORDS):
        return "real_scene"
    if any(kw.lower() in hay for kw in FLAT_BASE_KEYWORDS):
        return "flat_base"
    return "unknown"


def _as_float(v, default=0.0):
    try:
        return float(v)
    except (TypeError, ValueError):
        return default


def _aspect_of(img):
    ar = _as_float(img.get("aspect_ratio"), 0.0)
    if ar > 0:
        return ar
    w = _as_float(img.get("w"), 0.0)
    h = _as_float(img.get("h"), 0.0)
    return (w / h) if (w > 0 and h > 0) else 0.0


def _orient_of(img, ar):
    o = (img.get("orient") or "").strip().lower()
    if o in ("landscape", "portrait", "square"):
        return o
    if ar <= 0:
        return "square"
    if ar >= 1.25:
        return "landscape"
    if ar <= 0.8:
        return "portrait"
    return "square"


def _is_dense_info(vision):
    """识图描述/关键元素命中信息密集关键词 → True（照样 img2img，但走忠实保真提示词，见 DENSE_INFO_KEYWORDS 注释）。"""
    if not isinstance(vision, dict):
        return False
    hay = " ".join(
        [str(vision.get("description") or "")]
        + [str(x) for x in (vision.get("key_elements") or []) if isinstance(x, (str, int, float))]
    ).lower()
    product_terminal = any(
        kw.lower() in hay
        for kw in (
            "多终端", "播放终端", "终端设备", "电脑", "显示器", "平板", "手机", "vr", "眼镜",
            "头显", "multi-device", "terminal device", "computer", "monitor", "tablet",
            "smartphone", "phone", "vr headset", "headset", "goggles",
        )
    )
    dense_context = any(
        kw.lower() in hay
        for kw in (
            "截图", "界面", "表格", "图表", "数据", "列表", "控制台", "dashboard", "screenshot",
            "interface", "table", "chart", "graph", "data", "list", "console",
        )
    )
    if product_terminal and not dense_context:
        return False
    return any(kw in hay for kw in DENSE_INFO_KEYWORDS)


def _hero_target_aspect(orient, ar):
    if orient == "portrait":
        return "4:5"
    if orient == "landscape":
        return "21:9" if ar >= 2.0 else "16:9"
    return "1:1"


def _complement_text_zone(orient):
    # 横图配上下、竖图配左右（图文混排互补侧）。
    if orient == "landscape":
        return "bottom"
    if orient == "portrait":
        return "right"
    return "right"


def _text_zone(vision, orient):
    if isinstance(vision, dict):
        z = (vision.get("recommended_text_zone") or "").strip().lower()
        if z in ("left", "right", "top", "bottom", "center"):
            return z
    return _complement_text_zone(orient)


def _text_color(stats, is_background):
    mean = None
    if isinstance(stats, dict):
        bri = stats.get("brightness")
        if isinstance(bri, dict):
            mean = bri.get("mean")
    if isinstance(mean, (int, float)):
        return "dark" if mean >= BRIGHTNESS_DARK_TEXT_MIN else "light"
    # 无统计时：背景用法默认白字 + scrim（底图亮暗不可控），contain 小图默认深墨字（落在浅色正文页）。
    return "light" if is_background else "dark"


def _templates_for(usage_intent, orient, is_dense):
    if usage_intent == "discard":
        return []
    if usage_intent == "source_enhanced_bg":
        if orient == "landscape":
            return ["背景主导", "上图下文", "全幅浮层"]
        return ["背景主导", "全幅浮层"]
    if usage_intent == "source_enhanced_hero":
        if orient == "portrait":
            return ["左右产品剧场", "半包围文字"]
        if orient == "landscape":
            return ["上图下文", "左右产品剧场"]
        return ["中心产品 + 周围论点", "左右产品剧场"]
    if usage_intent == "gallery":
        return ["四宫格画廊"]
    if usage_intent == "small_evidence":
        return ["图像证据卡", "四宫格画廊"]
    # direct_contain
    if is_dense:
        return ["图像证据卡", "上图下文", "参数条 + 大图"]
    if orient == "portrait":
        return ["左右产品剧场", "半包围文字"]
    if orient == "landscape":
        return ["上图下文", "左右产品剧场"]
    return ["中心产品 + 周围论点", "左右产品剧场"]


def _display_role(usage_intent):
    """usage_intent → 显示档位（驱动 build 给多大的槽位，治「图被缩太小看不清」）。
    background=整页底图；foreground_hero=前景主视觉/半幅大图（≈半背景）；
    evidence_card=证据图（仍须可读、非缩略图）；gallery=画廊每格。"""
    if usage_intent == "discard":
        return "discard"
    if usage_intent == "source_enhanced_bg":
        return "background"
    if usage_intent == "gallery":
        return "gallery"
    if usage_intent == "small_evidence":
        return "evidence_card"
    # source_enhanced_hero / direct_contain
    return "foreground_hero"


def _image_role(usage_intent, enhance_style):
    """给设计/构建步的页面语义：这张图到底是背景、透明前景、保真文档还是证据画廊。"""
    if usage_intent == "discard":
        return "discard"
    if usage_intent == "source_enhanced_bg":
        return "background"
    if enhance_style == "cutout":
        return "foreground_cutout"
    if enhance_style == "dense":
        return "faithful_document"
    if usage_intent == "gallery":
        return "evidence_gallery"
    if usage_intent == "source_enhanced_hero":
        return "foreground_hero"
    return "evidence_gallery"


def _text_policy(enhance_style, has_text, strip_dense_caption=False):
    """图生图文字策略：背景/主体图去字，信息密集图才保留原数据文字。
    `strip_dense_caption=True`（2026-07-03，dense 且 content_type=screenshot_slide/poster 且有 embedded_text）：
    虽是 dense，但去掉的是装饰性 chrome 标题/标签而非数据本身——复用 `remove_all_text`（与 bg/hero/cutout
    去字语义相同："这段文字已被从图里抹掉"，不新造枚举值）。"""
    if enhance_style == "dense":
        return "remove_all_text" if strip_dense_caption else "preserve_data_text"
    if has_text:
        return "remove_all_text"
    return "avoid_new_text"


def _target_layer(usage_intent, enhance_style):
    if usage_intent == "discard":
        return "none"
    if usage_intent == "source_enhanced_bg":
        return "background"
    if usage_intent == "source_enhanced_hero" or enhance_style in ("cutout", "hero"):
        return "foreground"
    return "evidence"


def _layout_constraint(usage_intent):
    """usage_intent → 该图所在页的**版式硬约束**（设计步照读、不自行决定 render，治「有底图还套表格/卡墙划区」）：
    - fusion_no_cards：必走编辑式融合（图打底 / 半幅 hero + 文字浮前景 + scrim），**禁表格、禁悬浮卡片墙/网格划区**；
    - image_text_mixed：图文混排（contain 图 + 邻区文字），可少量 HTML，但勿在图上堆卡墙；
    - evidence_ok：低清证据图 / 画廊，证据卡 / 四宫格画廊布局 OK。"""
    if usage_intent == "discard":
        return "do_not_use"
    if usage_intent in ("source_enhanced_bg", "source_enhanced_hero"):
        return "fusion_no_cards"
    if usage_intent in ("small_evidence", "gallery"):
        return "evidence_ok"
    # direct_contain
    return "image_text_mixed"


# 「离散主体 / 产品特写」关键词 → 适合抠成**透明背景前景插图**（浮在编辑式背景上，原背景色不再与 PPT 冲突）。
DISCRETE_SUBJECT_KEYWORDS = (
    "产品", "设备", "器材", "物体", "零件", "部件", "工件", "螺栓", "螺丝", "元件", "电路板",
    "芯片", "镜头", "相机", "无人机", "机器人", "终端", "传感器", "模组", "样机", "样品",
    "硬件", "工具", "按键", "特写",
    "电脑", "显示器", "平板", "手机", "vr", "眼镜", "头显", "播放终端", "多终端", "终端设备",
    "设备组合", "多设备", "笔记本", "屏幕设备",
    # 轻量补（保守、皆为明确实体器件，不与 DENSE/SCENE 词重叠——避免误把截图/场景抠成透明）：
    "仪器", "仪表", "模块", "配件", "主板", "整机", "阀门", "电机", "马达", "电池", "摄像头",
    "product", "device", "component", "part", "lens", "camera", "drone", "robot",
    "sensor", "module", "hardware", "closeup", "close-up",
    "instrument", "gauge", "motherboard", "battery", "motor", "valve", "gadget",
    "computer", "monitor", "display", "tablet", "smartphone", "phone", "vr headset",
    "headset", "goggles", "viewer", "terminal device", "multi-device",
)
# 「场景 / 全景」关键词 → 留作背景/场景，不抠透明（抠了会丢环境信息）。
SCENE_KEYWORDS = (
    "全景", "现场", "车间", "厂房", "风光", "风景", "天际线", "城市", "星空", "场景",
    "驾驶舱", "机房", "工厂", "户外", "环境", "鸟瞰", "航拍",
    "panorama", "scene", "landscape", "cockpit", "factory", "skyline",
)


def _is_discrete_subject(vision):
    """识图描述像「离散主体/产品特写」（适合抠透明前景插图浮背景）而非「场景/全景」（留作背景）。
    两者都命中时**场景优先**（保守：宁可不抠也别误抠掉场景环境）。"""
    if not isinstance(vision, dict):
        return False
    hay = " ".join(
        [str(vision.get("description") or "")]
        + [str(x) for x in (vision.get("key_elements") or []) if isinstance(x, (str, int, float))]
    ).lower()
    if any(kw.lower() in hay for kw in SCENE_KEYWORDS):
        return False
    return any(kw.lower() in hay for kw in DISCRETE_SUBJECT_KEYWORDS)


# 「图上自带文字/水印/logo」关键词 → 该图若做背景【必须重绘成无文字版】（治用户诉求：图本身有文字就不能直接当背景）。
# 注：dense 信息图（截图/图表）本就含合法数据文字、走 dense 态保真，不在此列（has_text 只作用于 bg/hero 背景类图）。
EMBEDDED_TEXT_KEYWORDS = (
    "文字", "文本", "字样", "标题", "字幕", "水印", "标语", "标牌", "标注", "文案",
    "说明文字", "广告语", "商标", "字体", "印字", "题字", "横幅",
    "slogan", "logo", "banner", "text", "words", "caption", "watermark", "title",
    "label", "lettering", "typography", "subtitle", "wordmark",
)


def _embedded_text_list(vision):
    """识图结构化 `embedded_text` 字段（2026-07-03 加）：`[{"text","region"}, ...]`，图上没有烧进画面
    的文字则 `[]`。非法/非列表元素静默丢弃（容错，不因个别脏项让整张图的规划失败）。"""
    if not isinstance(vision, dict):
        return []
    items = vision.get("embedded_text")
    if not isinstance(items, list):
        return []
    out = []
    for it in items:
        if isinstance(it, dict) and str(it.get("text") or "").strip():
            out.append({"text": str(it["text"]).strip(), "region": str(it.get("region") or "").strip()})
        elif isinstance(it, str) and it.strip():
            out.append({"text": it.strip(), "region": ""})
    return out


def _has_embedded_text(vision):
    """图上是否烧着文字（该图做背景/去字重绘必须抹掉）。**结构化 `embedded_text` 字段优先**（2026-07-03，
    逐字记录了文字内容，判定即数据、不是猜）——`vision` 里存在该键就以它为准（含空列表 = 识图明确判过没有）。
    该键**不存在**（旧格式识图 JSON，无此字段）才退回对 description/key_elements 自由文本的关键词启发式。
    dense 信息图另走 dense 态保真、has_text 只调制 bg/hero 背景类图（dense 内的新分支见 _enhance_prompt）。"""
    if not isinstance(vision, dict):
        return False
    if "embedded_text" in vision:
        return bool(_embedded_text_list(vision))
    hay = " ".join(
        [str(vision.get("description") or "")]
        + [str(x) for x in (vision.get("key_elements") or []) if isinstance(x, (str, int, float))]
    ).lower()
    return any(kw.lower() in hay for kw in EMBEDDED_TEXT_KEYWORDS)


def _quote_embedded_text(embedded_text, limit=6):
    """把结构化 embedded_text 列表格式化成 prompt 里可引用的 "'文字'(位置), ..." 短语；空列表返回 ''。"""
    parts = []
    for it in (embedded_text or [])[:limit]:
        text = it.get("text") if isinstance(it, dict) else None
        if not text:
            continue
        region = it.get("region") if isinstance(it, dict) else ""
        parts.append(f"'{text}'" + (f" ({region})" if region else ""))
    return ", ".join(parts)


def _enhance_prompt(enhance_style, target_aspect, text_zone, bg_kind="unknown", has_text=False,
                     embedded_text=None, content_type=""):
    """图生图提示词骨架（英文，只表达「增强变换」；主体/真色由 --input-image 参考图携带，故无需翻译中文识图）。
    四态（由 plan_one 算定 enhance_style，bg/hero/cutout 三态再受 bg_kind 调制）：
      · dense  ：信息密集图（截图/图表/结构）→ **忠实保留版面与每个数据点/标签/坐标轴/框幅不变**，只清晰化、
                 去杂、统一 PPT 风格。⚠️ 数据图 img2img 有重绘/篡改风险，best-effort（用户明确要求照样重绘）；
                 **不加 no-text 尾**（这类图本就含合法文字/数据标签，须保留）。
                 例外（2026-07-03）：`content_type ∈ screenshot_slide|poster` 且有 `embedded_text` 时，
                 那些文字是"别人做好的整版截图/海报自带的标题/说明标签"这类**装饰性 chrome**——不是数据本身
                 （数据本身在 chart 类型里，坐标轴/图例数值仍走上面的纯保真分支），本页会有自己的标题、继续
                 保留原图标题会一图两标题/不可编辑，故走下面的「保结构去字」变体：结构/子图/非文字视觉细节
                 原样保留，但把识图逐字抄下来的文字明确列出要求去掉。
      · cutout ：离散主体特写 / **flat 底前景图**（主体+自有背景纹理）→ **抠成透明背景前景插图**
                 （连背景纹理一起去掉，主体浮在编辑式背景上，原背景不再与 PPT 两层底打架）。
      · bg     ：背景图扩成干净全幅底图——real_scene/unknown 续景 outpaint 扩展；flat_base 换 VI 同色系干净底。
      · hero   ：场景主视觉 → 保场景、清晰化、换干净底、扩到目标比例（不去背景）。
    `has_text=True`（识图发现图上自带文字/水印/logo，仅调制 bg/hero 背景类图）：放宽「严格保内容」、
    **强制抹掉所有文字重绘干净**——治用户诉求「图本身有文字就不能直接当背景，当背景必须重绘成无文字的」。
    `embedded_text` 非空时（2026-07-03）：抹字指令**引用识图逐字抄下来的实际文字**（而非泛泛的"has text,
    captions..."），指令越具体模型越容易照办；这段文字被抹掉后，规划条目仍原样保留 `embedded_text`，供
    设计阶段判断是否需要用真实 HTML 文字重新配出（write_plan_md 负责渲染，本函数只管生图提示词）。
    共同要点：保留原图主体/内容/真实配色不变；高清重绘到目标分辨率；统一加入 _QUALITY 质量/分辨率词。"""
    quoted = _quote_embedded_text(embedded_text)
    _PRESERVE = (
        "Use the attached image as the strict visual reference: preserve its main subject, content and real colors "
        "exactly — do not replace, restyle or invent a different subject. "
    )
    # 背景/hero 图自带文字时：换一段「保气质但允许重绘 + 强制抹字」前导，覆盖严格保内容（否则模型照搬原文字露字）。
    bg_preserve = _PRESERVE
    if has_text:
        if quoted:
            bg_preserve = (
                "Use the attached image as a style and composition reference: keep its overall scene, subject and "
                "real color palette, but redraw it. The original image has this exact baked-in text that must be "
                f"completely REMOVED, producing a clean, fully text-free background: {quoted}. Never reproduce or "
                "invent any text. "
            )
        else:
            bg_preserve = (
                "Use the attached image as a style and composition reference: keep its overall scene, subject and real "
                "color palette, but redraw it. The original image has text, captions, logos or watermarks on it — "
                "completely REMOVE all of that and produce a clean, fully text-free background; never reproduce or "
                "invent any text. "
            )
    if enhance_style == "dense":
        if has_text and quoted and content_type in ("screenshot_slide", "poster"):
            # 装饰性 chrome 文字（整版截图/海报自带的标题/说明标签，非图表数据）：保结构去字。
            return (
                _PRESERVE
                + "This is an information-dense composite image (screenshot / comparison slide / poster): "
                "faithfully keep the exact same layout, sub-images, comparison structure and every non-text visual "
                "detail unchanged, and keep the original framing and aspect ratio (do not crop, stretch or "
                "outpaint). However, the original image also has this exact baked-in caption/title text that must "
                f"be completely REMOVED, leaving clean empty space in its place: {quoted}. Never reproduce or "
                "invent any text. Only clean up noise and compression artifacts, sharpen blurry edges and "
                "re-render it crisply in a unified clean professional PPT style. " + _QUALITY
            )
        # 信息密集图（默认，含 content_type=chart）：忠实保真，只清晰化/去杂/统一风格（best-effort，有重绘
        # 风险）；不加 no-text 尾（须保留数据标签——图表坐标轴/图例数值是数据本身，不是装饰性 chrome）。
        return (
            _PRESERVE
            + "This is an information-dense image (screenshot / chart / diagram / table): faithfully keep the exact "
            "same layout, every data point, label, axis, value and structure unchanged, and keep the original "
            "framing and aspect ratio (do not crop, stretch or outpaint). Only clean it up — remove noise and "
            "compression artifacts, sharpen blurry edges and re-render it crisply in a unified clean professional "
            "PPT style. " + _QUALITY
        )
    if enhance_style == "cutout":
        # 离散主体特写 / flat 底前景图 → 透明背景前景插图（浮在编辑式背景之上，原背景纹理不再与 PPT 冲突/两层底打架）。
        return (
            _PRESERVE
            + "Redraw it in high resolution, keep the subject complete, centered and sharp, "
            "**remove the original background and any background texture entirely and output the isolated subject on "
            "a fully transparent background (transparent alpha channel, PNG RGBA) — no backdrop, no scene, no "
            "texture, only the subject**, "
            "upscale and sharpen details, clean even product lighting, subject fills the frame. "
            + _QUALITY + "crisp cut-out edges. " + _NO_TEXT_TAIL
        )
    if enhance_style == "bg":
        if bg_kind == "flat_base":
            # 纯色/白底/棚拍底 → 换成 VI 同色系干净背景，不保留原杂底。
            return (
                bg_preserve
                + f"Redraw it in high resolution and place the subject on a clean, uncluttered full-bleed "
                f"{target_aspect} background that exactly fills the slot: replace the plain or messy original base "
                "with a professional VI-toned backdrop in the same color family as the subject (subtle gradient, "
                "no clutter), upscale and sharpen details, "
                f"leave a calm low-detail area on the {text_zone} side for overlay text. "
                + _QUALITY + "cinematic depth. " + _NO_TEXT_TAIL
            )
        # real_scene / unknown → 续景 outpaint 扩展成干净全幅底图。
        return (
            bg_preserve
            + f"Redraw it in high resolution and extend it into a clean, uncluttered full-bleed {target_aspect} background "
            "that exactly fills the slot: outpaint and intelligently complete the missing edges by naturally continuing "
            "the existing scene (do not stretch or distort), upscale and sharpen details, remove distracting clutter, "
            f"soft even studio lighting, leave a calm low-detail area on the {text_zone} side for overlay text. "
            + _QUALITY + "cinematic depth. " + _NO_TEXT_TAIL
        )
    # hero（场景型主视觉，换干净底）
    return (
        bg_preserve
        + f"Redraw it in high resolution into a clean {target_aspect} hero shot that exactly fills the slot: "
        "keep the subject centered and complete, outpaint and intelligently complete any missing area by naturally "
        "extending the scene (do not stretch or distort), upscale and sharpen details, "
        "replace the messy or low-quality background with a clean minimal backdrop, "
        "professional product-photography lighting, subject fills the frame. " + _QUALITY + _NO_TEXT_TAIL
    )


def plan_one(img):
    """对单张客户图做确定性版式/增强规划，返回规划 dict。

    ① 全图生图政策：**所有客户图一律 enhance_required=true（不再直接用原图）**——
       合格+背景图 → source_enhanced_bg；合格+非背景 → source_enhanced_hero；低清/坏比例维持现有 bg/hero；
       dense（截图/图表）照样 img2img 但走忠实保真提示词。唯一保守例外 = **无 vision 盲态**（不知是否截图、
       无法选对增强提示词，维持 enhance=false）。display_role / layout_constraint 等 DISPLAY 语义不变。
    ② 图生图按背景类型分流（_background_kind）：real_scene→hero / flat_base+离散主体→cutout / flat_base 铺底→bg。"""
    file = img.get("file")
    w_val = _as_float(img.get("w"), 0.0)
    h_val = _as_float(img.get("h"), 0.0)
    ar = _aspect_of(img)
    orient = _orient_of(img, ar)
    vision = img.get("vision") if isinstance(img.get("vision"), dict) else None
    stats = img.get("stats") if isinstance(img.get("stats"), dict) else None

    low_res = bool(su._is_low_res_for_background(img))
    bad_aspect = bool(ar and (ar < BAD_ASPECT_MIN or ar > BAD_ASPECT_MAX))
    quality = "low_res" if low_res else ("bad_aspect" if bad_aspect else "ok")
    is_dense = _is_dense_info(vision)
    bg_suitable = bool(vision and vision.get("suitable_as_background") is True)
    has_vision = vision is not None
    bg_kind = _background_kind(vision)  # ② 背景类型分流（real_scene / flat_base / unknown）
    has_text = _has_embedded_text(vision)  # 图上自带文字/水印 → bg/hero 背景类图必须重绘成无文字版（治「带字图当背景露字」）
    embedded_text = _embedded_text_list(vision)  # 识图逐字抄下来的图上文字（2026-07-03，供去字提示词引用 + 设计阶段重配）
    # 识图结构化字段（2026-07-02 加，识图 prompt 同步产出；旧 vision JSON 缺字段 → None/空串，走既有分支）：
    #   relevant_to_topic=false → 弃用（坠机资讯图与「制造+影像档案」主题负相关，识图早写了「强烈建议不采用」
    #   但只活在散文 notes 里，规划器消费不到 → 被 source_usage_check「全部用上」硬塞进 deck 的事故根因）。
    #   content_type=screenshot_slide → 整版 PPT 截图：强制按信息密集图走 direct_contain（contain 框图展示、
    #   忠实保真、绝不铺背景），不管 _is_dense_info 的关键词启发有没有命中。
    relevant = vision.get("relevant_to_topic") if has_vision else None
    content_type = str(vision.get("content_type") or "").strip().lower() if has_vision else ""
    if content_type == "screenshot_slide":
        is_dense = True

    # ① 默认全图生图重绘；唯一保守例外是无 vision 盲态（下面分支置 false）。
    enhance_required = True
    target_aspect = None

    if has_vision and relevant is False:
        # 弃用：与主题不相关/负面暗示的图不进 deck（豁免「全部用上」，见 source_usage_check）。
        usage_intent = "discard"
        enhance_required = False
    elif is_dense:
        # 信息密集图（截图/图表/结构）：照样 img2img，但忠实保真（保版面/数据/框幅）；不背景化、保持原始比例。
        usage_intent = "direct_contain"
        target_aspect = f"{int(w_val)}:{int(h_val)}" if (w_val > 0 and h_val > 0) else None
    elif not has_vision:
        # 无识图（无多模态模型）：唯一保守例外——不冒险图生图（可能是截图、无法选对提示词），低清做证据小图，否则 contain。
        usage_intent = "small_evidence" if (low_res or bad_aspect) else "direct_contain"
        enhance_required = False
    elif bg_suitable and not _is_discrete_subject(vision):
        # 合格/低清/坏比例的背景图都图生图重绘成高清干净全幅背景。
        # 【离散主体(产品/设备)即便被识图标 suitable_as_background 也排除在外 → 落下面 else 分支】。
        usage_intent = "source_enhanced_bg"
        target_aspect = "16:9"
    else:
        # 合格/低清/坏比例的非背景图都图生图重绘成高清主视觉。
        # 含【被识图误标 bg 的离散主体/产品】：用户红线——主体+自有底纹的图绝不当整页背景（放我们背景/渐变上=
        # 两层底打架、走位背景也不行），强制走前景主视觉、下面 enhance_style 再把它抠成透明前景插图。
        usage_intent = "source_enhanced_hero"
        target_aspect = _hero_target_aspect(orient, ar)

    is_background = usage_intent == "source_enhanced_bg"
    text_zone = _text_zone(vision, orient)
    text_color = _text_color(stats, is_background)
    display_role = _display_role(usage_intent)
    # ② 增强样式（识图驱动）：dense=忠实保真 / bg=干净全幅底图 / hero=保场景换干净底 / cutout=离散主体抠透明前景插图。
    if not enhance_required:
        enhance_style = None
    elif is_dense:
        enhance_style = "dense"
    elif usage_intent == "source_enhanced_bg":
        # 背景图恒 bg（real_scene 续景 / flat_base 换 VI 底，由 _enhance_prompt 按 bg_kind 区分文案）。
        enhance_style = "bg"
    else:  # source_enhanced_hero（前景主视觉）：按背景类型决定保场景 vs 抠透明。
        if bg_kind == "real_scene":
            enhance_style = "hero"  # 真实场景：保场景、清晰化、换干净底（不抠，否则丢环境信息）。
        elif bg_kind == "flat_base" or _is_discrete_subject(vision):
            # flat 底（纯色/渐变/纹理/棚拍）的前景图，或离散主体 → 抠透明前景插图：主体浮我们页面背景上、
            # 不带自己那块底（治用户：带「前景主体+自有背景纹理」的图直接放我们背景/渐变上=两层底打架、当背景也不行）。
            enhance_style = "cutout"
        else:  # unknown 且非离散主体 → 当场景型处理、换干净底。
            enhance_style = "hero"

    # dense 且是"整版截图/海报"自带装饰性 chrome 文字（非图表数据）→ 去字保结构（2026-07-03）。
    strip_dense_caption = (
        enhance_style == "dense" and has_text and bool(embedded_text)
        and content_type in ("screenshot_slide", "poster")
    )

    entry = {
        "file": file,
        "w": img.get("w"),
        "h": img.get("h"),
        "aspect_ratio": round(ar, 3) if ar else None,
        "orient": orient,
        "quality": quality,
        "is_dense_info": is_dense,
        "suitable_as_background": bg_suitable,
        "has_vision": has_vision,
        # ② 背景类型（识图驱动图生图分流）：real_scene / flat_base / unknown。
        "background_kind": bg_kind,
        # 图上是否自带文字/水印（True → bg/hero 重绘强制抹字，治「带字图当背景露字」）。
        "has_embedded_text": has_text,
        "usage_intent": usage_intent,
        # 版式硬约束（设计步照读、不自行决定 render）：有底图的页禁表格/卡墙、走编辑式融合。
        "layout_constraint": _layout_constraint(usage_intent),
        # 显示档位 + 尺寸下限 + 缩放上限（治「客户图缩成角落小图看不清 / 低清原图被放大糊」）：
        "display_role": display_role,
        "min_canvas_fraction": MIN_CANVAS_FRACTION[display_role],
        "max_upscale": MAX_UPSCALE,
        "enhance_required": enhance_required,
        "enhance_style": enhance_style,
        "image_role": _image_role(usage_intent, enhance_style),
        "text_policy": _text_policy(enhance_style, has_text, strip_dense_caption),
        "target_layer": _target_layer(usage_intent, enhance_style),
        "enhance_target_aspect": target_aspect,
        "recommended_templates": _templates_for(usage_intent, orient, is_dense),
        "text_zone": text_zone,
        "text_color": text_color,
    }
    # ③ 章节锚定（治张冠李戴）：来源章节/邻近文案/出处从 material 原样透传——此前 entry 把
    # section 丢弃（仅 gallery 图以 gallery_group 幸存），设计步只能按识图语义配页，客户图被
    # 配到无关主题页。透传后设计步以 section 为配页第一锚点，source_usage_check 据此校验错位。
    sec = (img.get("section") or "").strip()
    if sec:
        entry["section"] = sec
    near = (img.get("near_text") or "").strip()
    if near:
        entry["near_text"] = near[:120]
    if img.get("origin"):
        entry["origin"] = img.get("origin")
    if isinstance(vision, dict) and vision.get("description"):
        entry["vision_description"] = vision["description"]
    if isinstance(vision, dict) and vision.get("key_message"):
        entry["key_message"] = vision["key_message"]
    if embedded_text:
        # 逐字记录的图上原文（2026-07-03）：图生图会把这些字抹掉，非空才挂——供 write_plan_md 渲染
        # 「去字后待重配」提示，设计阶段据此判断是否需要用真实 HTML 文字重新配出。
        entry["embedded_text"] = embedded_text
    if enhance_required and file:
        prompt = _enhance_prompt(
            enhance_style, target_aspect, text_zone, bg_kind, has_text,
            embedded_text=embedded_text, content_type=content_type,
        )
        entry["enhanced_file"] = f"enhanced_{file}"
        entry["enhance_prompt"] = prompt
    return entry


# 可组画廊的（非背景）用途：前景主视觉 / contain 图 / 证据小图。背景图（source_enhanced_bg）绝不进四宫格。
# 注：全图生图政策下这些图多已 enhance_required=true；分组只改 DISPLAY 字段，**保留各图既有增强决策**
# （enhance_required / enhance_style / enhanced_file / enhance_prompt 原样带过——画廊每格照样图生图增强到高清）。
_GALLERY_OK_INTENTS = ("source_enhanced_hero", "direct_contain", "small_evidence")


def _apply_gallery(entries):
    """同章节图片数 ≥ 阈值且都是非背景用途 → 标 gallery_group，建议四宫格画廊。"""
    by_section = {}
    for e, raw in entries:
        sec = (raw.get("section") or "").strip()
        if sec:
            by_section.setdefault(sec, []).append(e)
    for sec, group in by_section.items():
        if len(group) < GALLERY_MIN_PER_SECTION:
            continue
        if all(e["usage_intent"] in _GALLERY_OK_INTENTS for e in group):
            for e in group:
                e["gallery_group"] = sec
                e["usage_intent"] = "gallery"
                e["layout_constraint"] = "evidence_ok"
                e["display_role"] = "gallery"
                e["image_role"] = _image_role("gallery", e.get("enhance_style"))
                e["target_layer"] = _target_layer("gallery", e.get("enhance_style"))
                e["min_canvas_fraction"] = MIN_CANVAS_FRACTION["gallery"]
                e["recommended_templates"] = ["四宫格画廊"]


def build_plan(build_dir):
    build_dir = os.path.abspath(build_dir)
    material = _load_json(os.path.join(build_dir, "material.json"), {}) or {}
    base_images = [im for im in (material.get("images") or []) if isinstance(im, dict) and im.get("file")]

    paired = [(plan_one(im), im) for im in base_images]
    _apply_gallery(paired)
    images = [e for e, _ in paired]
    enhance_entries = []
    for e in images:
        if e.get("enhance_required") and e.get("file"):
            enhance_entries.append(
                {
                    "file": e["enhanced_file"],
                    "mode": "image-to-image",
                    "source_file": e["file"],
                    "aspect": e["enhance_target_aspect"],
                    "prompt": e["enhance_prompt"],
                    "image_role": e.get("image_role"),
                    "text_policy": e.get("text_policy"),
                    "target_layer": e.get("target_layer"),
                    "enhance_style": e.get("enhance_style"),
                }
            )

    return {
        "has_source": bool(material.get("has_source")),
        "image_count": len(images),
        "enhance_count": len(enhance_entries),
        "images": images,
        "enhance_entries": enhance_entries,
    }


def _load_json(path, default=None):
    try:
        with open(path, encoding="utf-8-sig") as f:
            return json.load(f)
    except Exception:
        return default


_USAGE_CN = {
    "source_enhanced_bg": "整页背景【需图生图扩到 16:9 干净底图】",
    "source_enhanced_hero": "主视觉 hero【需图生图修比例/提清晰/换干净背景】",
    "direct_contain": "原图 contain 展示（不裁不变形，勿放大勿背景化）",
    "small_evidence": "证据小图 / 侧图（低清，原图小用即可）",
    "gallery": "多图画廊（四宫格 / 横向带）",
}

_ROLE_CN = {
    "background": "整页背景大图",
    "foreground_hero": "前景主视觉 / 半幅大图（≈半背景，至少占画布 30%）",
    "evidence_card": "证据图（必须可读、绝非角落缩略图，≥12% 画布）",
    "gallery": "画廊每格（≥10% 画布）",
}

_CONSTRAINT_CN = {
    "fusion_no_cards": "编辑式融合（图打底/半幅 hero + 文字浮前景 + scrim）—— 🚫该页禁表格、禁悬浮卡片墙/网格划区",
    "image_text_mixed": "图文混排（contain 图 + 邻区文字），可少量 HTML，勿在图上堆卡墙",
    "evidence_ok": "低清证据图 / 画廊，证据卡 / 四宫格画廊布局 OK",
}


def write_plan_md(build_dir, plan):
    L = ["# 客户图版式 + 图生图增强规划（确定性产出，设计步据此选模板、勿再逐图心算）\n"]
    L.append(
        "> 来源 material.json。每张图的 usage_intent / **显示档位 + 槽位最小占比 + 缩放上限** / 是否图生图 / 目标比例 / 模板 / "
        "文字落区与深浅均已算定；图生图提示词见 source_layout_plan.json 的 enhance_prompt。\n"
        "> **尺寸铁律（治『客户图缩太小看不清 / 低清图放大糊』）**：每张图按 `display_role` 给够大的槽（至少占 `min_canvas_fraction` 画布、"
        "绝不缩成角落小图/底部小条）；原图**缩放 ≤1×**（绝不放大超原生像素糊掉），要显示得比原生大就走图生图重绘到目标分辨率。\n"
        "> **enhance_required 的图**：设计步必须写成 `route=source-enhanced`、引用 `enhanced_<file>`；生图前引擎确定性把这些条目并进 img_plan.json。\n"
    )
    if not plan["images"]:
        L.append("\n（无客户图 —— 纯 topic / 纯文档无图，跳过本规划。）\n")
    else:
        L.append(
            f"\n共 {plan['image_count']} 张客户图，其中 {plan['enhance_count']} 张**必须图生图增强**。\n"
        )
        for i, e in enumerate(plan["images"], 1):
            L.append(f"\n## 图 {i}：{e['file']}")
            wh = f"{e.get('w', '?')}×{e.get('h', '?')}"
            L.append(
                f"- 尺寸/比例/朝向：{wh}，比例 {e.get('aspect_ratio', '?')}，{e['orient']}；"
                f"质量 **{e['quality']}**" + ("（信息密集图，保真勿增强）" if e["is_dense_info"] else "")
            )
            L.append(f"- 用途：**{e['usage_intent']}** — {_USAGE_CN.get(e['usage_intent'], '')}")
            L.append(
                f"- 显示档位：**{e.get('display_role', '?')}** — {_ROLE_CN.get(e.get('display_role'), '')}；"
                f"**缩放上限 ≤{e.get('max_upscale', MAX_UPSCALE)}×**（原图绝不放大糊；要更大走图生图）；"
                f"槽位**至少占画布 {int(e.get('min_canvas_fraction', 0) * 100)}%**（绝不缩成角落小图/底部小条）"
            )
            L.append(
                f"- 版式约束：**{e.get('layout_constraint', '?')}** — {_CONSTRAINT_CN.get(e.get('layout_constraint'), '')}"
            )
            L.append(
                f"- 图层语义：image_role=`{e.get('image_role')}`，target_layer=`{e.get('target_layer')}`，"
                f"text_policy=`{e.get('text_policy')}`（背景/主体图与带装饰性说明字的截图去字；真图表数据标签才保留）"
            )
            if e["enhance_required"]:
                _style_cn = {
                    "bg": "背景图·扩成干净全幅底图",
                    "hero": "场景主视觉·换干净底",
                    "cutout": "离散主体特写·**抠透明背景前景插图**（作前景特写浮在编辑式背景上，原背景色不再与 PPT 冲突）",
                    "dense": "信息密集图·**忠实保留版面与数据结构**清晰化去杂（best-effort，有重绘/篡改风险）",
                }.get(e.get("enhance_style"), "")
                L.append(
                    f"- 🚨 图生图：是（{_style_cn}）→ 生成 `{e['enhanced_file']}`（目标比例 {e['enhance_target_aspect']}），"
                    "deck 引用增强图、保留 `data-source-file` 映射；提示词见 json。"
                )
            else:
                L.append("- 图生图：否（原图直接用）")
            L.append(f"- 推荐模板（对齐 layout-composition §2.2）：{ ' / '.join(e['recommended_templates']) }")
            L.append(
                f"- 文字落区：{e['text_zone']}（避让重点区）；文字深浅："
                + ("深墨字（亮底）" if e["text_color"] == "dark" else "白字（暗底/背景，配 scrim）")
            )
            if e.get("section"):
                L.append(
                    f"- 来源章节：**{e['section']}**（🚨 配页锚点：必须配到覆盖本章节内容的页，"
                    "识图语义只用于章节内挑页；仅该章节无对应页时才按语义另配）"
                )
            if e.get("near_text"):
                L.append(f"- 原文邻近文案：{e['near_text']}")
            if e.get("key_message"):
                L.append(f"- 🚨 图表核心结论（该页 key_point/evidence 须呼应）：{e['key_message']}")
            if e.get("vision_description"):
                L.append(f"- 识图内容（文案须呼应）：{e['vision_description']}")
            et = e.get("embedded_text")
            if et:
                quoted = "、".join(f"「{it['text']}」" for it in et if it.get("text"))
                L.append(
                    "- 🚨 原图文字已在图生图阶段去除，如信息有价值需在本页用真实 HTML 文字重新配出"
                    f"（不必逐字照抄，按论点整合；纯水印/logo 可直接丢弃）：{quoted}"
                )
    with open(os.path.join(os.path.abspath(build_dir), "source_layout_plan.md"), "w", encoding="utf-8") as f:
        f.write("\n".join(L).strip() + "\n")


def ensure_img_plan(build_dir):
    """把规划里的图生图条目 union 进 img_plan.json（按 file 去重）——保证『必须图生图』的图一定会被生成。"""
    build_dir = os.path.abspath(build_dir)
    plan = _load_json(os.path.join(build_dir, "source_layout_plan.json"))
    if not isinstance(plan, dict):
        print("ENSURE_IMG_PLAN_SKIP: 无 source_layout_plan.json，跳过。")
        return 0
    entries = plan.get("enhance_entries") or []
    if not entries:
        print("ENSURE_IMG_PLAN_OK: 无需图生图增强的客户图（注入 0 条）。")
        return 0

    img_plan_path = os.path.join(build_dir, "img_plan.json")
    existing = _load_json(img_plan_path)
    if not isinstance(existing, list):
        existing = []
    have = {e.get("file") for e in existing if isinstance(e, dict)}
    injected = 0
    for ent in entries:
        if ent.get("file") and ent["file"] not in have:
            existing.append(ent)
            have.add(ent["file"])
            injected += 1
    with open(img_plan_path, "w", encoding="utf-8") as f:
        json.dump(existing, f, ensure_ascii=False, indent=2)
    print(
        f"ENSURE_IMG_PLAN_OK: 注入 {injected} 条图生图条目（规划共 {len(entries)} 条，"
        f"img_plan.json 现 {len(existing)} 条）→ {img_plan_path}"
    )
    return 0


def reconcile_source_extensions(build_dir, design_path=None):
    """把 design.json / img_plan.json 里客户图引用的扩展名，对齐 source_assets.json 的真实文件名。

    根因（2026-07-05 真机 src_9 事故）：design 阶段的 LLM 在 design.json 的 `visual.source_file`/
    `enhanced_file` 与 best-effort `img_plan.json` 条目里，凭常见约定猜扩展名（如 `.jpg`），但客户图
    实际落盘扩展名由 stage_extract 决定、可能是任意格式（真机是 `.png`）——猜错时 image-to-image
    生图找不到 source_file，直接 degraded=gradient-png 兜底占位；由于占位文件仍然「存在」（不是
    404），deck.html 的 `<img onerror>` 永远不会触发，页面静默用一张低质量渐变图顶替真实产品图，
    且同一张源图在 `source_layout_plan.json` 里已有的正确条目（正确扩展名、且已成功生成）被晾在
    一边——生成了却没被任何页引用，白白浪费一次生图。

    修法：按 stem（去扩展名）比对 `source_assets.json` 的真实文件列表，把两处扩展名不匹配的
    `source_file`/`file`/`enhanced_file` 就地纠正为真实扩展名；纠正后 `img_plan.json` 若出现同
    `file` 的重复条目（原猜测条目纠正后与已有正确条目撞车），去重保留先出现的一条。"""
    build_dir = os.path.abspath(build_dir)
    assets = _load_json(os.path.join(build_dir, "source_assets.json"))
    images = assets.get("images") if isinstance(assets, dict) else None
    if not isinstance(images, list) or not images:
        print("RECONCILE_EXT_SKIP: 无 source_assets.json / 无客户图，跳过。")
        return 0

    stem_to_real = {
        su._stem(im["file"]): im["file"]
        for im in images
        if isinstance(im, dict) and im.get("file")
    }

    def _fix_name(name):
        if not isinstance(name, str) or not name:
            return name, False
        prefix = "enhanced_" if name.startswith("enhanced_") else ""
        base = name[len(prefix):]
        real = stem_to_real.get(su._stem(base))
        if not real or real == base:
            return name, False
        return prefix + real, True

    fixed_count = 0

    design_path = design_path or os.path.join(build_dir, "design.json")
    design = _load_json(design_path)
    design_changed = False
    if isinstance(design, dict) and isinstance(design.get("pages"), list):
        for p in design["pages"]:
            visual = p.get("visual") if isinstance(p, dict) else None
            if not isinstance(visual, dict):
                continue
            for key in ("source_file", "enhanced_file"):
                new_val, changed = _fix_name(visual.get(key))
                if changed:
                    visual[key] = new_val
                    design_changed = True
                    fixed_count += 1
        if design_changed:
            with open(design_path, "w", encoding="utf-8") as f:
                json.dump(design, f, ensure_ascii=False, indent=2)

    img_plan_path = os.path.join(build_dir, "img_plan.json")
    plan = _load_json(img_plan_path)
    plan_changed = False
    deduped = 0
    if isinstance(plan, list) and plan:
        seen_files = set()
        result = []
        for e in plan:
            if not isinstance(e, dict):
                result.append(e)
                continue
            for key in ("file", "source_file", "enhanced_file"):
                new_val, changed = _fix_name(e.get(key))
                if changed:
                    e[key] = new_val
                    plan_changed = True
                    fixed_count += 1
            fkey = e.get("file")
            if fkey and fkey in seen_files:
                deduped += 1
                plan_changed = True
                continue  # 纠正扩展名后与既有条目撞车 → 丢弃这条重复的，保留先出现者
            if fkey:
                seen_files.add(fkey)
            result.append(e)
        if plan_changed:
            with open(img_plan_path, "w", encoding="utf-8") as f:
                json.dump(result, f, ensure_ascii=False, indent=2)

    if fixed_count == 0 and deduped == 0:
        print("RECONCILE_EXT_OK: 未发现扩展名不匹配，无需修正。")
    else:
        print(
            f"RECONCILE_EXT_OK: 修正 {fixed_count} 处扩展名不匹配"
            + (f"，去重 {deduped} 条重复条目" if deduped else "")
            + "（design.json/img_plan.json 已对齐 source_assets.json 真实文件名）。"
        )
    return 0


def ensure_ai_img_plan(build_dir, design_path=None):
    """把 design.json 里 route∈{ai-A,ai-B} 页的文生图条目确定性 union 进 img_plan.json。

    约定：
    - `side=full` 的 ai-* 是整页背景，文件名 `ai_p<page>.png`；
    - 非 full 的 ai-* 是前景插图/特写，文件名 `ai_p<page>_fg.png`；
      背景层仍由 ensure_page_backgrounds 用 `ai_p<page>.png` 补齐。

    这样防止同一张 `ai_pN.png` 既当背景又当前景，造成第 7 页那类重复贴图。"""
    build_dir = os.path.abspath(build_dir)
    if not design_path:
        design_path = os.path.join(build_dir, "design.json")
    design = _load_json(design_path)
    pages = design.get("pages") if isinstance(design, dict) else None
    if not isinstance(pages, list):
        print("ENSURE_AI_IMG_PLAN_SKIP: 无 design.json / pages，跳过。")
        return 0

    img_plan_path = os.path.join(build_dir, "img_plan.json")
    existing = _load_json(img_plan_path)
    if not isinstance(existing, list):
        existing = []
    have = {e.get("file") for e in existing if isinstance(e, dict)}

    injected = 0
    for p in pages:
        if not isinstance(p, dict):
            continue
        visual = p.get("visual")
        if not isinstance(visual, dict):
            continue
        if str(visual.get("route", "")).lower() not in ("ai-a", "ai-b"):
            continue
        prompt = visual.get("prompt")
        if not isinstance(prompt, str) or not prompt.strip():
            continue  # 无提示词没法生图，留给 .ai-fallback 渐变兜底
        side = str(visual.get("side") or "").lower()
        is_foreground_ai = side and side not in ("full", "none")
        ai_file = f"ai_p{p.get('page')}_fg.png" if is_foreground_ai else f"ai_p{p.get('page')}.png"
        if ai_file in have:
            continue
        existing.append(
            {
                "file": ai_file,
                "mode": "text-to-image",
                "aspect": visual.get("aspect") or "16:9",
                "prompt": prompt,
                "target_layer": "foreground" if is_foreground_ai else "background",
            }
        )
        have.add(ai_file)
        injected += 1

    with open(img_plan_path, "w", encoding="utf-8") as f:
        json.dump(existing, f, ensure_ascii=False, indent=2)
    print(
        f"ENSURE_AI_IMG_PLAN_OK: 注入 {injected} 条文生图 AI 背景条目"
        f"（img_plan.json 现 {len(existing)} 条）→ {img_plan_path}"
    )
    return 0


# 确定性氛围底图的逐页轻变体（按页号取模，给相邻补背景的页一点光位差异、不靠 LLM、不随机）。
_ATMOS_VARIANTS = (
    "soft radial glow in the upper left",
    "gentle diagonal light sweeping from the lower right",
    "calm horizontal gradient band across the frame",
    "subtle centered vignette with quiet depth",
)


def _vi_tone_hint(build_dir, design):
    """尽力取一个【纯 ASCII 的 VI 色调词】喂确定性氛围背景提示词（不调 LLM、不翻译中文避免乱码）；
    取不到返回 ''（走通用氛围——背景照样生成，只是不带具体色调）。
    探序：design.json 顶层 vi 类字段 → build/{chosen_vi,vi}.txt 首行。含 CJK/杂字符则放弃。"""
    palette_map = {
        "aegis-vector": "deep industrial blue and clean white palette, cool chrome lines, aviation-grade precision, no shield symbol",
        "aegis vector": "deep industrial blue and clean white palette, cool chrome lines, aviation-grade precision, no shield symbol",
        "aqua-glass": "light blue and white glass palette, crisp black-blue typography, clean luminous surfaces",
        "aqua glass": "light blue and white glass palette, crisp black-blue typography, clean luminous surfaces",
        "comfort-vision": "warm off-white paper, deep ink green, restrained rust-orange signal accents",
        "comfort vision": "warm off-white paper, deep ink green, restrained rust-orange signal accents",
        "obsidian-optics": "near-black graphite, cold white highlights, restrained signal red, precision camera hardware mood",
        "obsidian optics": "near-black graphite, cold white highlights, restrained signal red, precision camera hardware mood",
        "precision-horizon": "minimal gray-white product launch palette, black typography, refined hardware photography mood",
        "precision horizon": "minimal gray-white product launch palette, black typography, refined hardware photography mood",
        "precision-horizon-dark": "graphite black product theater, warm orange material highlights, premium hardware mood",
        "precision horizon dark": "graphite black product theater, warm orange material highlights, premium hardware mood",
        "nebula-console": "deep space blue-black palette, electric blue and cyan edge light, commercial technology mood",
        "nebula console": "deep space blue-black palette, electric blue and cyan edge light, commercial technology mood",
        "violet-meridian": "white base with violet and cobalt-blue light paths, clear AI workspace mood",
        "violet meridian": "white base with violet and cobalt-blue light paths, clear AI workspace mood",
        "ember-prism": "white base with strong red and warm orange accents, energetic AI product launch mood",
        "ember prism": "white base with strong red and warm orange accents, energetic AI product launch mood",
    }
    cand = None
    if isinstance(design, dict):
        for k in ("vi", "vi_name", "visual_identity", "theme", "vi_template"):
            v = design.get(k)
            if isinstance(v, str) and v.strip():
                cand = v
                break
    if cand is None:
        for name in ("chosen_vi.txt", "vi.txt"):
            path = os.path.join(build_dir, name)
            try:
                if os.path.isfile(path):
                    with open(path, encoding="utf-8") as f:
                        txt = f.read().strip()
                    if txt:
                        cand = txt.splitlines()[0]
                        break
            except Exception:  # noqa: BLE001  色调词只是锦上添花，读不到不影响背景生成
                pass
    if not isinstance(cand, str):
        return ""
    s = cand.strip().lower()
    mapped = palette_map.get(s.replace("_", "-")) or palette_map.get(" ".join(s.replace("-", " ").replace("_", " ").split()))
    if mapped:
        return mapped
    for pre in ("vi-", "vi_", "vi "):
        if s.startswith(pre):
            s = s[len(pre):]
    s = " ".join(s.replace("-", " ").replace("_", " ").split())
    # 仅「纯 ASCII 字母+空格」的核心名才用（如 "aqua glass"）；含 CJK/数字/杂符则放弃走通用氛围。
    if s and all((c.isascii() and (c.isalpha() or c.isspace())) for c in s):
        return f"in a {s} color palette"
    return ""


def _sanitize_image_prompt(prompt):
    if not prompt:
        return prompt
    replacements = {
        "abstract blueprint": "low-interference cinematic technical background",
        "blueprint background": "clean low-interference technical background",
        "crosshair": "subtle optical alignment lines",
        "target reticle": "subtle optical alignment lines",
        "shield": "precision hardware silhouette",
        "aegis": "industrial precision",
        "18 thumbnails": "a few clean visual evidence moments",
        "thumbnail grid": "editorial image strip",
        "many thumbnails": "selected large visual moments",
        "UI card": "minimal parameter overlay",
        "ui card": "minimal parameter overlay",
        "floating cards": "small restrained parameter overlays",
        "dashboard cards": "small restrained parameter overlays",
        "matrix background": "cinematic depth background",
    }
    out = prompt
    for src, dst in replacements.items():
        out = re.sub(re.escape(src), dst, out, flags=re.I)
    return out


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


I2I_PROMPT_MARKERS = (
    "use the attached image",
    "attached image",
    "strict visual reference",
    "preserve its main subject",
    "preserve its main subject, content and real colors",
    "input image",
    "source_file",
    "source image",
)


def _looks_like_image_to_image_prompt(prompt):
    if not isinstance(prompt, str) or not prompt.strip():
        return False
    hay = prompt.lower()
    return any(marker in hay for marker in I2I_PROMPT_MARKERS)


def _complementary_bg_prompt_from_page(page, tone_hint):
    """为「semantic_image_prompt 本身写成了 i2i 指令」的页生成互补背景，而不是把该指令原样喂给 t2i。

    这类页的前景主体已经由某张 `enhanced_src_K` 承担；背景只负责气氛、空间和文字净区。
    如果把 "Use the attached image..." 直接喂给 text-to-image，模型没有参考图时会随机生成瓶子、
    盾牌、设备等无关主体，所以这里强制生成不抢戏的互补背景。（`route==source-enhanced` 的页现由
    `ensure_page_backgrounds` 直接跳过整个背景注入，不会走到这里——2026-07-03 真机 3/5/6/8/9 页事故。）
    """
    takeaway = _page_text(page.get("one_sentence_takeaway") or page.get("key_point") or page.get("title"))
    visual_story = _page_text(page.get("visual_story"))
    text_zone = _page_text(page.get("text_overlay_zone") or page.get("safe_text_zone") or page.get("text_zone"))
    tone = f"{tone_hint}, " if tone_hint else ""
    subject = f"supporting the idea: {takeaway}. {visual_story}." if (takeaway or visual_story) else ""
    return (
        "Complementary low-interference background for an Apple / DJI style product-detail PPT page, "
        "designed to sit behind a separate customer-image foreground or hero cutout. "
        f"{subject} Keep a spacious clean text-safe zone at {text_zone or 'one side'}; "
        f"{tone}premium aviation and industrial atmosphere, soft depth, subtle light, elegant negative space, "
        "no standalone product, no bottle, no medicine, no cosmetic container, no shield symbol, no UI cards, "
        "no thumbnail collage, no diagram, no chart, no text, no words, no letters, no logos, no watermark"
        + _QUALITY
        + _NO_TEXT_TAIL
    )


def _semantic_bg_prompt_from_page(page, tone_hint):
    """优先把 design.json 的页面级语义转成背景/场景生图提示词。

    设计阶段若已经写了 semantic_image_prompt，就尊重它；否则用页面主句、视觉故事和主视觉层
    生成一个“产品详情页式语义背景”。精确信息页仍不让 AI 画结构图，而是生成低干扰语义底图。
    """
    if not isinstance(page, dict):
        return ""
    semantic = _page_text(page.get("semantic_image_prompt"))
    if semantic and not semantic.lower().startswith("html-svg"):
        if _looks_like_image_to_image_prompt(semantic):
            return _complementary_bg_prompt_from_page(page, tone_hint)
        semantic = _sanitize_image_prompt(semantic)
        if "no text" not in semantic.lower():
            semantic = semantic.rstrip(" .") + ", no text, no words, no letters, no logos, no watermark"
        return semantic + _NO_TEXT_TAIL

    style = _page_text(page.get("composition_style"))
    grammar = _page_text(page.get("page_grammar"))
    takeaway = _page_text(page.get("one_sentence_takeaway") or page.get("key_point") or page.get("title"))
    visual_story = _page_text(page.get("visual_story"))
    main_visual = _page_text(page.get("main_visual_layer") or page.get("visual_focus"))
    text_zone = _page_text(page.get("text_overlay_zone") or page.get("safe_text_zone") or page.get("text_zone"))
    tone = f"{tone_hint}, " if tone_hint else ""

    if not any((takeaway, visual_story, main_visual)):
        return ""

    if style == "data-visual" or grammar == "data-visual":
        return (
            "Low-interference premium product-detail-page background that supports an editable HTML/SVG "
            f"data visualization about {takeaway}. "
            f"{tone}soft cinematic depth, calm negative space for overlay text and charts, no charts drawn, "
            "no diagrams, no numbers, no text, no words, no letters, no logos, no watermark"
            + _QUALITY
            + _NO_TEXT_TAIL
        )

    return (
        "Premium Apple / DJI style product-detail-page visual background, cinematic and photographic, "
        f"visually representing: {takeaway}. {visual_story}. Primary visual idea: {main_visual}. "
        f"Keep a clean text-safe zone at {text_zone or 'one side'}; "
        f"{tone}high-end editorial lighting, realistic depth, elegant composition, no clutter, "
        "no text, no words, no letters, no captions, no logos, no watermark"
        + _QUALITY
        + _NO_TEXT_TAIL
    )


def _atmos_bg_prompt(tone_hint, page_no, page=None):
    """确定性合成「产品详情页式底图」文生图提示词。

    优先使用页面级 semantic_image_prompt / visual_story / takeaway，避免无图页只生成廉价抽象渐变；
    实在没有页面语义时才退为 VI 氛围背景。
    """
    semantic_prompt = _semantic_bg_prompt_from_page(page, tone_hint)
    if semantic_prompt:
        return semantic_prompt
    try:
        idx = int(page_no)
    except (TypeError, ValueError):
        idx = 0
    variant = _ATMOS_VARIANTS[idx % len(_ATMOS_VARIANTS)]
    tone = f"{tone_hint}, " if tone_hint else ""
    return (
        "Professional atmospheric editorial background for a premium product detail page "
        "(Apple / DJI style): " + variant + ", soft cinematic gradient depth, subtle texture and gentle "
        "light, generous calm low-detail negative space for overlay text, no diagrams, no text, no words, "
        "no letters, " + tone + _QUALITY + _NO_TEXT_TAIL
    )


def ensure_page_backgrounds(build_dir, design_path=None):
    """把【每个无背景图的内容页】确定性补一条 VI 氛围文生图底图条目 union 进 img_plan.json
    （按约定名 `ai_p<page>.png`、按 file 去重幂等）。

    真凶（真机 deck.html 实证）：设计 LLM 给约一半内容页留 `route:none/html`（无背景图）→ build 无底图可挂 →
    那些页退化成「白底 + 卡片墙/表格」（§0.7 编辑式三层「前景禁卡墙」规则只对**有背景**的编辑式页生效）。
    本函数把「每页必须有背景层」从弱模型手里收成确定性：凡某页既无客户图（`route=source-enhanced`，任意
    usage_intent——hero/contain/gallery/bg 皆算「该页已有真实视觉」）、又无设计选定且带提示词的 ai-* 底图
    （ensure_ai_img_plan 已注入）、img_plan 里也没有 `ai_p<page>.png` → 优先按该页 semantic_image_prompt /
    visual_story / takeaway 补语义化产品详情页背景；信息不足时才退为 VI 同色系氛围底。卡片墙因此「每页都成
    编辑式页」被既有规则自动挡掉（Leak B 是 Leak A 的下游症状）。

    2026-07-03 真机 3/5/6/8/9 页事故修正：此前只有 `usage_intent==source_enhanced_bg` 才跳过独立 AI 背景
    注入，`source_enhanced_hero`/`direct_contain`/`gallery`（页面已经在用客户真图做主视觉/画廊）仍会被强插
    一张完全无关的 `ai_p<page>.png`——真机验证出：与客户真图同主题重复（页3，两张厂房图叠一页）、或
    visual_focus 被背景 prompt 去内容化后落入"通用室内"陈词滥调完全跑题（页5/6/9，办公桌+窗帘）。
    对照组：页7（无客户图，纯 AI 背景 + VI 渐变兜底）效果干净——证明"客户图页不需要再叠一张竞争性 AI 图"
    这个判断成立。现在只要该页 `route=="source-enhanced"`（有任意客户图视觉）就跳过独立背景注入，
    `.edit-bg` 交给 build_batch 已有的 `--vi-fallback` VI 渐变兜底（页7已验证效果，不需要新机制）。

    跑序：在 `--ensure-img-plan`（客户图）+ `--ensure-ai-img-plan`（LLM 选的 ai-*）**之后**。build_batch 按约定名
    `ai_p<page>.png` 引用 + onerror 渐变兜底，故**无需回写 design.json**（build 早于 gate 的时序安全）。
    `generate_from_plan` 文生图失败退渐变 PNG，三方对齐、优雅退化。ppt 独占（webppt 不调用此脚本）。"""
    build_dir = os.path.abspath(build_dir)
    if not design_path:
        design_path = os.path.join(build_dir, "design.json")
    design = _load_json(design_path)
    pages = design.get("pages") if isinstance(design, dict) else None
    if not isinstance(pages, list):
        print("ENSURE_PAGE_BG_SKIP: 无 design.json / pages，跳过。")
        return 0

    img_plan_path = os.path.join(build_dir, "img_plan.json")
    existing = _load_json(img_plan_path)
    if not isinstance(existing, list):
        existing = []
    have = {e.get("file") for e in existing if isinstance(e, dict)}

    tone_hint = _vi_tone_hint(build_dir, design)

    injected = 0
    for p in pages:
        if not isinstance(p, dict):
            continue
        page_no = p.get("page")
        if page_no is None:
            continue
        ai_file = f"ai_p{page_no}.png"
        if ai_file in have:
            continue  # ai-* 已注入 / 本函数已补过 → 去重
        visual = p.get("visual") if isinstance(p.get("visual"), dict) else {}
        route = str(visual.get("route", "")).lower()
        # 已有【真实视觉】的页跳过：① 客户图整页底 / 前景 hero / contain 框图 / 画廊——任意 usage_intent，
        #   只要该页在用客户真图，就不需要再叠一张无关竞争性 AI 背景（2026-07-03 真机 3/5/6/8/9 页事故：
        #   source_enhanced_hero/direct_contain/gallery 曾被排除在外，仍强插 ai_p<page>.png，导致同主题
        #   重复或彻底跑题）；② 设计选定且带提示词的 ai-* 底图（ensure_ai_img_plan 管）。
        # 注：route 为 source（前景 contain 原图直用）、html、none、缺 visual —— 才是真【没有背景图】，
        #     照样补氛围底图；`route=="source-enhanced"` 一律视为已有真实视觉，`.edit-bg` 交给 build_batch
        #     既有的 VI 渐变兜底（--vi-fallback，页7 无客户图对照组已验证效果，不需要新机制）。
        if route == "source-enhanced":
            continue
        prompt_existing = visual.get("prompt")
        if route in ("ai-a", "ai-b") and isinstance(prompt_existing, str) and prompt_existing.strip():
            continue
        existing.append(
            {
                "file": ai_file,
                "mode": "text-to-image",
                "aspect": "16:9",
                "prompt": _atmos_bg_prompt(tone_hint, page_no, p),
            }
        )
        have.add(ai_file)
        injected += 1

    with open(img_plan_path, "w", encoding="utf-8") as f:
        json.dump(existing, f, ensure_ascii=False, indent=2)
    print(
        f"ENSURE_PAGE_BG_OK: 为 {injected} 个无背景内容页补 VI 氛围底图条目"
        f"（img_plan.json 现 {len(existing)} 条）→ {img_plan_path}"
    )
    return 0


def reconcile_missing(build_dir):
    """生图后**确定性兜底**（治「图生图缺图 → deck 死链空框」）：遍历 source_layout_plan.json 的
    enhance_entries，凡 `assets/<enhanced_file>` **缺失**（gen 中断/早退/某条没轮到，连降级占位都没写）
    且其 `assets/<source_file>` 原图存在 → **把原图拷一份顶上**（宁可用没增强的原图、绝不留空框/断图）。
    已生成的增强图**不覆盖**；连原图也缺的记 warning 不崩。恒 return 0。

    与 generate_from_plan.mjs 的逐条降级互补：那个只在 gen 真迭代到该条时才写占位，本函数是
    **gen 之后、独立于 gen 是否覆盖**的最终兜底。ppt 独占（webppt 不调用此脚本）。"""
    build_dir = os.path.abspath(build_dir)
    assets = os.path.join(build_dir, "assets")
    plan = _load_json(os.path.join(build_dir, "source_layout_plan.json"))
    entries = (plan or {}).get("enhance_entries") or [] if isinstance(plan, dict) else []
    if not entries:
        print("RECONCILE_MISSING_OK: 无图生图增强条目（注入 0 张兜底）。")
        return 0

    copied = []
    missing_source = []
    for ent in entries:
        if not isinstance(ent, dict):
            continue
        f = ent.get("file")
        src = ent.get("source_file")
        if not f:
            continue
        dst_path = os.path.join(assets, f)
        if os.path.isfile(dst_path):
            continue  # 真增强图已生成 → 绝不覆盖
        src_path = os.path.join(assets, src) if src else None
        if src_path and os.path.isfile(src_path):
            try:
                os.makedirs(assets, exist_ok=True)
                shutil.copyfile(src_path, dst_path)
                copied.append((src, f))
            except Exception as e:  # noqa: BLE001  兜底绝不崩
                missing_source.append(f"{f}(拷贝失败:{e})")
        else:
            missing_source.append(f"{f}(原图 {src} 也缺)")

    msg = f"RECONCILE_MISSING_OK: 回退拷贝 {len(copied)} 张缺失增强图（原图顶上，防 deck 空框）"
    if copied:
        msg += "：" + ", ".join(f"{s}→{d}" for s, d in copied)
    if missing_source:
        msg += f"；⚠️ {len(missing_source)} 张无法兜底: {missing_source}"
    print(msg)
    return 0


def main() -> int:
    parser = argparse.ArgumentParser(
        description="客户图版式/图生图增强确定性规划器（读 material.json → source_layout_plan.json/md）"
    )
    parser.add_argument("--build", default="./build", help="摄取产物目录（默认 ./build）")
    parser.add_argument(
        "--ensure-img-plan",
        action="store_true",
        help="reconcile 模式：把规划的图生图条目 union 进 img_plan.json（生图前调用）",
    )
    parser.add_argument(
        "--ensure-ai-img-plan",
        action="store_true",
        help="reconcile 模式：把 design.json 的 route=ai-A/ai-B 页【文生图 AI 背景】条目 union 进 img_plan.json"
        "（约定名 ai_p<page>.png，不靠设计 LLM 记得写；生图前调用）",
    )
    parser.add_argument(
        "--design",
        default=None,
        help="design.json 路径（--ensure-ai-img-plan 用；缺省取 <build>/design.json）",
    )
    parser.add_argument(
        "--reconcile-extensions",
        action="store_true",
        help="reconcile 模式：把 design.json/img_plan.json 里客户图扩展名对齐 source_assets.json 真实"
        "文件名（治 design LLM 猜错扩展名致生图找不到源图、静默退化占位图；在 --ensure-img-plan 之后、"
        "生图之前调用）",
    )
    parser.add_argument(
        "--ensure-page-backgrounds",
        action="store_true",
        help="reconcile 模式：为【无背景图的内容页】补 VI 氛围文生图底图条目 union 进 img_plan.json"
        "（约定名 ai_p<page>.png，治「route:none/html 页无底图→退化白底卡片墙」；在 --ensure-ai-img-plan 之后调用）",
    )
    parser.add_argument(
        "--reconcile-missing",
        action="store_true",
        help="兜底模式：生图后把缺失的 enhanced 派生图从原图拷贝顶上（防 deck 死链空框；生图后、导出前调用）",
    )
    args = parser.parse_args()

    if args.ensure_img_plan:
        return ensure_img_plan(args.build)

    if args.reconcile_extensions:
        return reconcile_source_extensions(args.build, args.design)

    if args.ensure_ai_img_plan:
        return ensure_ai_img_plan(args.build, args.design)

    if args.ensure_page_backgrounds:
        return ensure_page_backgrounds(args.build, args.design)

    if args.reconcile_missing:
        return reconcile_missing(args.build)

    plan = build_plan(args.build)
    build_dir = os.path.abspath(args.build)
    os.makedirs(build_dir, exist_ok=True)
    with open(os.path.join(build_dir, "source_layout_plan.json"), "w", encoding="utf-8") as f:
        json.dump(plan, f, ensure_ascii=False, indent=2)
    write_plan_md(build_dir, plan)
    print(
        f"SOURCE_LAYOUT_PLANNED: {plan['image_count']} 张客户图，{plan['enhance_count']} 张需图生图增强 "
        f"→ {os.path.join(build_dir, 'source_layout_plan.json')}"
    )
    return 0


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