#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Rewrite PPT image prompts so generated images stay page-bound.

This script is intentionally deterministic. It does not invent design content;
it binds each image plan item to the current user request, page takeaway,
composition role, VI tone, and source-image plan. The goal is to prevent generic
"sleek device / product photography" prompts from producing random monitors,
controllers, bottles, or other unrelated objects.

生产者-闸门契约（单一词表真相源，治「机器自产自拦」halt）
========================================================
本脚本是 t2i prompt 的**唯一生产/净化点**，下游 `image_plan_lint.py` 只做兜底验证。
因此本脚本必须保证产出**必过** lint：直接 import lint 的黑名单
（STRUCTURAL/BAD_AESTHETIC/BACKGROUND_TEXT_MARKER/GENERIC_OBJECT_RISK）作为
`RISKY_TERMS`——lint 加词，这里自动跟上，永不再出现「rewrite 拼进 design 字段的
中文词（如页 visual_focus 里的『行业缩略图』、页标题里的『架构/流程』）被 lint
拦下 → 整条工作流确定性 halt」的死端（2026-07-01 真机事故）。
落点三层：① anchor/标题/takeaway/visual_focus 等**机器拼接段**先剥 RISKY 词；
② LLM 原 prompt 命中 RISKY 词 → 强制重组成安全的页面绑定 prompt（= yaml 声明的
「结构图回退」语义：结构交 HTML 层，AI 图退化为安全底图，确定性完成不必等人修）；
③ 最终 prompt 再整体剥一遍作闭环兜底。i2i（客户图增强）提示词不经此净化——
lint 对 image-to-image 本就豁免，保真意图不同。
"""

from __future__ import annotations

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

# 同目录直跑（python3 .../image_prompt_rewrite.py）时 sys.path[0] 即脚本目录；
# 被 importlib/测试等其它方式加载时补一道 __file__ 目录守卫，保证 lint 可 import。
_SCRIPTS_DIR = str(Path(__file__).resolve().parent)
if _SCRIPTS_DIR not in sys.path:
    sys.path.insert(0, _SCRIPTS_DIR)
import image_plan_lint as _lint  # noqa: E402

# lint 黑名单的并集 = 本脚本禁止在 t2i prompt 里出现的词（单一真相源在 lint）。
RISKY_TERMS = (
    list(_lint.STRUCTURAL_TERMS)
    + list(_lint.BAD_AESTHETIC_TERMS)
    + list(_lint.BACKGROUND_TEXT_MARKER_TERMS)
    + list(_lint.GENERIC_OBJECT_RISK_TERMS)
)


def _find_risky(text: str) -> list[str]:
    """text 里非否定式命中的 lint 黑名单词（复用 lint 的否定式判定）。"""
    return _lint._find_non_negated_terms(text, RISKY_TERMS)


def _strip_risky_terms(text: str) -> str:
    """从 text 里剥掉所有非否定式命中的 RISKY 词（用于机器拼接段与最终闭环兜底）。"""
    text = str(text or "")
    guard = 0
    hits = _find_risky(text)
    while hits and guard < 6:
        for term in hits:
            text = re.sub(re.escape(term), " ", text, flags=re.IGNORECASE)
        text = re.sub(r"[ \t]{2,}", " ", text)
        hits = _find_risky(text)
        guard += 1
    return text.strip()


PAGE_FILE_RE = re.compile(r"ai_p(\d+)(?:_fg)?\.(?:png|jpe?g|webp)$", re.IGNORECASE)

GENERIC_RISK_TERMS = [
    "professional product photography",
    "sleek device",
    "futuristic screen",
    "generic monitor",
    "consumer electronics",
    "game controller",
    "cosmetic bottle",
    "medicine bottle",
    "shampoo bottle",
]

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,
)

FOREGROUND_STRUCTURE_RE = re.compile(
    r"(?:\d+\s*张|\d+\s*个|\d+\s*行|\d+\s*列|\d+\s*组|横排|竖排|并排|中部|顶部|底部|左侧|右侧|"
    r"大字|主标|文字|文案|takeaway|标签|编号|序号|图表|柱图|柱状|饼图|折线|表格|数据表|架构|流程|对比图|"
    r"时间线|时间轴|箭头|胶囊|节点|连线|\bSVG\b|"
    # 2026-07-02 真机事故（ai_p23）：design visual_focus 里的「三组'一'短标」漏过词表 →
    # 生图模型照画三条带字药丸横在背景正中、与 HTML 标题叠字。带字元件类词全部拒收。
    r"短标|角标|徽标|字样|清单|列表|药丸|"
    r"comparison chart|chart|diagram|timeline|arrow|arrows|capsules?|nodes?|labels?|text|headline|"
    r"badges?|chips?|pills?|list items?)",
    re.I,
)

NEGATIVE_OBJECTS = (
    "no game controller, no cosmetic bottle, no medicine bottle, no shampoo bottle, "
    "no generic consumer electronics, no random monitor, no keyboard, no UI mockup, "
    "no text, no logo, no letters, no watermark"
)

CHINESE_ANCHOR_RE = re.compile(r"[\u4e00-\u9fff][\u4e00-\u9fffA-Za-z0-9·+\-/]{1,11}")
ENGLISH_ANCHOR_RE = re.compile(r"\b[A-Za-z][A-Za-z0-9+\-/]{3,}\b")
ANCHOR_STOPWORDS = {
    "主题", "指令", "用户", "要求", "生成", "做成", "页面", "背景", "图片", "文字", "内容", "设计",
    "视觉", "风格", "中文", "文案", "标题", "素材", "客户", "产品", "场景", "重点", "需要",
    "必须", "用于", "高清", "比例", "信息", "专业", "方案", "系统", "能力", "价值", "结构",
    "用户原始输入与目标", "主题/指令", "文件作为基础", "生成一套专业中文", "专业中文",
    "presentation", "visual", "image", "slide", "title", "core", "message", "premium",
    "product", "detail", "page", "background", "foreground", "style", "clean", "high",
    "resolution", "text", "safe", "zone",
}


def _load_json(path: Path, default: Any) -> Any:
    if not path.exists():
        return default
    try:
        return json.loads(path.read_text(encoding="utf-8"))
    except Exception:
        return default


def _load_text(path: Path) -> str:
    if not path.exists():
        return ""
    return path.read_text(encoding="utf-8", errors="replace")


def _text_of(value: Any) -> 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 _add_anchor(out: list[str], value: str) -> None:
    value = value.strip(" ，,。.;；:：()（）[]【】<>《》\"'")
    if len(value) < 2:
        return
    low = value.lower()
    if low in ANCHOR_STOPWORDS:
        return
    if FOREGROUND_STRUCTURE_RE.search(value):
        return
    # 拒收含 lint 黑名单词的 anchor（如「行业缩略图」）：拼进 prompt 会被下游闸门拦。
    if _find_risky(value):
        return
    if value not in out:
        out.append(value)


def _extract_anchors(*values: Any, limit: int = 12) -> list[str]:
    text = " ".join(_text_of(v) for v in values)
    anchors: list[str] = []
    for match in CHINESE_ANCHOR_RE.findall(text):
        _add_anchor(anchors, match)
        if len(anchors) >= limit:
            return anchors
    for match in ENGLISH_ANCHOR_RE.findall(text):
        _add_anchor(anchors, match)
        if len(anchors) >= limit:
            return anchors
    return anchors


def _has_anchor(text: str, anchors: list[str]) -> bool:
    hay = text.lower()
    return any(anchor.lower() in hay for anchor in anchors)


def _has_generic_risk(text: str) -> bool:
    hay = text.lower()
    return any(term in hay for term in GENERIC_RISK_TERMS)


def _page_map(design: dict[str, Any]) -> dict[int, dict[str, Any]]:
    pages: dict[int, dict[str, Any]] = {}
    for page in design.get("pages", []) if isinstance(design, dict) else []:
        if not isinstance(page, dict):
            continue
        try:
            pages[int(page.get("page"))] = page
        except Exception:
            continue
    return pages


def _page_no_from_file(file_name: str) -> int | None:
    match = PAGE_FILE_RE.search(file_name)
    if not match:
        return None
    try:
        return int(match.group(1))
    except ValueError:
        return None


def _page_for_item(item: dict[str, Any], pages: dict[int, dict[str, Any]]) -> dict[str, Any] | None:
    try:
        page_no = int(item.get("page"))
        if page_no in pages:
            return pages[page_no]
    except Exception:
        pass
    file_name = str(item.get("file") or "")
    page_no = _page_no_from_file(file_name)
    if page_no in pages:
        return pages[page_no]
    source_file = str(item.get("source_file") or "")
    needles = [v for v in (file_name, source_file) if v]
    if needles:
        for page in pages.values():
            blob = json.dumps(page, ensure_ascii=False)
            if any(n in blob for n in needles):
                return page
    return None


def _deck_meta_anchor(deck_meta: dict[str, Any] | None) -> dict[str, str]:
    """从 design.json 顶层 deck_meta 提取产品外观/客户身份锚，剥净 RISKY 词后返回。

    2026-07-07 真机 p9 复盘：页面文案省略主语（"拆除 WiFi 模块"不重复"全景相机"）时，
    纯靠该页 title/takeaway 提取的 anchors 完全抓不到"这是客户自己的产品"这层信息，
    t2i 生图凭空画出无关设备（通用电路板/工控盒），而非客户真实产品外观。deck_meta
    是设计阶段读全部 vision.json 后**只写一次**的深度信息，这里读出来供每页 t2i 复用，
    不依赖任何单页文案是否显式提及产品名。"""
    deck_meta = deck_meta if isinstance(deck_meta, dict) else {}
    product = _strip_risky_terms(str(deck_meta.get("product_identity") or "")).strip()
    customer = _strip_risky_terms(str(deck_meta.get("customer_context") or "")).strip()
    return {"product_identity": product, "customer_context": customer}


def _page_context(
    page: dict[str, Any] | None,
    user_request: str,
    deck_meta: dict[str, Any] | None = None,
) -> dict[str, str]:
    page = page or {}
    title = str(page.get("title") or "")
    takeaway = str(page.get("one_sentence_takeaway") or page.get("key_point") or title)
    visual_focus = str(page.get("visual_focus") or page.get("visual_story") or "")
    grammar = str(page.get("page_grammar") or page.get("composition_style") or "")
    text_zone = str(page.get("safe_text_zone") or page.get("text_overlay_zone") or page.get("text_zone") or "left")
    visual_role = str(page.get("visual_role") or page.get("primary_visual_type") or "")
    vi_style = str(
        page.get("vi")
        or page.get("style")
        or page.get("visual_style")
        or page.get("theme")
        or ""
    )
    anchors = _extract_anchors(
        title,
        takeaway,
        visual_role,
        page.get("visual_story"),
        page.get("semantic_image_prompt"),
        page.get("visual"),
        page.get("blocks"),
        user_request,
    )
    anchor_text = ", ".join(anchors[:8]) or "the user-provided topic and page-specific subject"
    ctx = {
        "title": title,
        "takeaway": takeaway,
        "visual_focus": visual_focus,
        "grammar": grammar,
        "text_zone": text_zone,
        "visual_role": visual_role,
        "vi_style": vi_style,
        "user_request": user_request[:800],
        "anchors": anchor_text,
    }
    ctx.update(_deck_meta_anchor(deck_meta))
    return ctx


# 含数字/金额/百分比的锚点碎片（如「核心总投入约」「3 万元」）：文字渲染型生图模型（Seedream 类）
# 会把它们照画成假图表标注——背景/增强层锚点一律剔除。
DIGITY_ANCHOR_RE = re.compile(r"[0-9０-９%％]|万元|亿|千万")
# 句子碎片判定：CHINESE_ANCHOR_RE 从 takeaway 整句里切出来的片段常含功能词（的/把/被/约/相当于…），
# 或顶到 12 字上限（截断即非名词）；场景名词锚不该有这些形态。
SENTENCE_FRAGMENT_RE = re.compile(r"[的了是把被让将约]|相当于|等于|成为|沦为")
ANCHOR_MAX_NOUN_LEN = 11


def _scene_anchor_text(anchor_text: str) -> str:
    """背景/i2i 层锚点净化：只留场景名词类短语（去数字/金额与句子碎片、限 6 个），空了给通用兜底。
    页面绑定（anti-generic）靠这些名词，不靠标题/正文原句——原句会被模型当文字画进图里。"""
    kept = []
    for a in (anchor_text or "").split(","):
        a = a.strip()
        if not a or DIGITY_ANCHOR_RE.search(a) or SENTENCE_FRAGMENT_RE.search(a):
            continue
        # 12 字上限截断只发生在 CJK 整句切片上（英文名词天然带词界，不设限）。
        if re.search(r"[一-鿿]", a) and len(a) > ANCHOR_MAX_NOUN_LEN:
            continue
        kept.append(a)
        if len(kept) >= 6:
            break
    return ", ".join(kept) or "the user-provided topic and page-specific scene"


def _style_tone(ctx: dict[str, str]) -> str:
    vi = ctx.get("vi_style") or "the selected VI palette and current user style request"
    return (
        f"premium product-detail page visual, cinematic but restrained, clean lighting, "
        f"high resolution, coherent with {vi}, not decorative clutter"
    )


def _safe_background_focus(text: str) -> str:
    """Background prompts must not ask the image model to draw labels/numbers.

    Editable PPT text, chapter marks, labels, and numbers belong to HTML/SVG
    foreground layers. If these words leak into a background image prompt, image
    models reliably bake non-editable symbols into the bitmap.
    """
    text = str(text or "").strip()
    if not text:
        return "clean page-relevant atmosphere with clear visual direction"
    if (
        BACKGROUND_TEXT_MARKER_RE.search(text)
        or FOREGROUND_STRUCTURE_RE.search(text)
        or _find_risky(text)
    ):
        return "low-interference complementary background atmosphere with clean negative space, not foreground labels or charts"
    return text


def _is_data_or_html_page(page: dict[str, Any] | None) -> bool:
    if not isinstance(page, dict):
        return False
    text = " ".join(
        str(page.get(k) or "")
        for k in (
            "page_grammar",
            "composition_style",
            "visual_role",
            "primary_visual_type",
            "semantic_image_prompt",
        )
    ).lower()
    return any(term in text for term in ("data-visual", "html-svg", "chart", "axis", "diagram", "架构", "流程", "图表"))


def _product_identity_clause(ctx: dict[str, str]) -> str:
    """deck 级产品外观/客户身份锚——独立于本页文案是否显式提及产品名（见 _deck_meta_anchor）。
    空值时返回空字符串，不影响没有真实产品照的示意型 deck。"""
    product = ctx.get("product_identity") or ""
    customer = ctx.get("customer_context") or ""
    if not product and not customer:
        return ""
    parts = []
    if product:
        parts.append(
            f"Product visual consistency (this deck's real product — match its actual appearance, "
            f"never invent a different-looking device): {product}."
        )
    if customer:
        parts.append(f"Customer/industry context: {customer}.")
    return " " + " ".join(parts)


def _background_prompt(ctx: dict[str, str], data_page: bool) -> str:
    # 🚫 背景层提示词**绝不携带页标题/正文原句/数字/图表描述**（2026-07-03 ai_p9 真机事故：
    # "Slide title: 投入有限，对冲无限. Core message: 核心总投入约 3 万元… Visual focus: 成本拆解 HTML 表 +
    # 投入/对冲对比柱状图" 被 Seedream 类文字渲染型模型照着画出一整版烘字假幻灯片，与 HTML 真卡互相遮挡）。
    # 页面绑定（anti-generic）只靠去数字化的场景名词锚；表格/图表/标题由 HTML 层承载，背景只管氛围与留白。
    if data_page:
        subject = (
            "low-interference data-space background, subtle material depth, "
            "large clean negative space reserved for the editable HTML/SVG data graphics drawn on top"
        )
        visual_focus = "pure atmosphere only; all data visuals are drawn by the HTML layer, not in this image"
    else:
        subject = (
            "realistic page-specific scene or product environment derived from the slide topic, "
            "visual focus supports the slide message without adding unrelated objects"
        )
        visual_focus = _safe_background_focus(ctx["visual_focus"])
    return (
        f"{subject}. Scene inspiration keywords (mood reference only — never render these words or any writing): "
        f"{_scene_anchor_text(ctx['anchors'])}. Visual focus: {visual_focus}."
        f"{_product_identity_clause(ctx)} "
        f"Text safe zone: {ctx['text_zone']} — keep it as large clean negative space. "
        f"{_style_tone(ctx)}. absolutely no text of any kind, no chinese characters, no digits, "
        f"no charts, no tables, no diagrams, no slide-like layout, {NEGATIVE_OBJECTS}."
    )


def _foreground_prompt(ctx: dict[str, str]) -> str:
    return (
        "single complete page-specific product, object, or scene detail as a foreground cutout, "
        f"matching slide message: {_strip_risky_terms(ctx['takeaway'])}. Topic anchors: {ctx['anchors']}."
        f"{_product_identity_clause(ctx)} "
        "transparent or clean dark background, complete subject, no cropping through the main body, "
        f"{_style_tone(ctx)}. {NEGATIVE_OBJECTS}."
    )


def _rewrite_t2i(
    item: dict[str, Any],
    page: dict[str, Any] | None,
    user_request: str,
    deck_meta: dict[str, Any] | None = None,
) -> tuple[str, bool, str]:
    original = str(item.get("prompt") or "")
    ctx = _page_context(page, user_request, deck_meta)
    data_page = _is_data_or_html_page(page)
    role = str(item.get("role") or item.get("target_layer") or ctx["visual_role"]).lower()
    file_name = str(item.get("file") or "").lower()
    is_foreground_file = "_fg." in file_name
    is_background = not is_foreground_file and role not in ("foreground", "fg", "cutout")

    force_rewrite = False
    reason = []
    if "use the attached image" in original.lower() or "preserve its main subject" in original.lower():
        force_rewrite = True
        reason.append("i2i_prompt_in_t2i")
    anchors = _extract_anchors(
        page,
        item.get("note"),
        item.get("role"),
        item.get("target_layer"),
        user_request,
    )
    if _has_generic_risk(original) and not _has_anchor(original, anchors):
        force_rewrite = True
        reason.append("generic_prompt_without_domain_anchor")
    if not original.strip() or not _has_anchor(original, anchors):
        force_rewrite = True
        reason.append("missing_domain_anchor")
    if is_background and (
        BACKGROUND_TEXT_MARKER_RE.search(original)
        or BACKGROUND_TEXT_MARKER_RE.search(ctx["visual_focus"])
        or FOREGROUND_STRUCTURE_RE.search(original)
        or FOREGROUND_STRUCTURE_RE.search(ctx["visual_focus"])
    ):
        force_rewrite = True
        reason.append("background_text_marker_conflict")
    # 背景 prompt 携带页面文案/图表描述（"Slide title:" 等旧模板遗留、或 LLM 自拼）→ 必须重组：
    # 下游 lint 的 slide_copy 检查会拦（生产者产出必过闸门契约）；旧 img_plan 复跑也借此收敛到新模板。
    if is_background and _lint._find_slide_copy_terms(original):
        force_rewrite = True
        reason.append("slide_copy_in_background_prompt")
    # 原 prompt 命中 lint 黑名单（结构图/坏审美/背景文字标记/泛消费品）→ 机器重组成
    # 安全的页面绑定 prompt——「结构图回退」的确定性实现：结构交 HTML 层，AI 图退化为安全底图。
    risky = _find_risky(original)
    if risky:
        force_rewrite = True
        reason.append("risky_terms:" + "|".join(str(t) for t in risky[:4]))

    if not is_background:
        prompt = _foreground_prompt(ctx)
    else:
        prompt = _background_prompt(ctx, data_page)

    if force_rewrite:
        # 闭环兜底：模板为静态安全文案、动态段已剥 RISKY 词；万一跨段拼接仍构成命中，整体再剥一遍，
        # 保证「rewrite 产出必过 lint」的不变量成立（did_change 按真实差异报，二跑幂等 changed=0）。
        residual = _find_risky(prompt)
        if residual:
            prompt = _strip_risky_terms(prompt)
        return prompt, prompt != original, ",".join(reason)

    # force_rewrite=False：原 prompt 本身已过审（有锚点/无风险词/无背景文字冲突），但"有锚点"只是指
    # 页面局部词命中，不代表提过客户真实产品外观——该页文案完全可能没提产品名（见本函数头注真机 p9
    # 复盘），产品身份锚必须补齐，不能因为原 prompt "看起来还行" 就放过。幂等：锚文本已存在则不重复拼。
    appended = []
    identity_clause = _product_identity_clause(ctx)
    if identity_clause and identity_clause.strip() not in original:
        original = original.rstrip(" .") + "." + identity_clause
        appended.append("product_identity_anchor")
    if NEGATIVE_OBJECTS.lower() not in original.lower():
        original = original.rstrip(" .") + ". " + NEGATIVE_OBJECTS + "."
        appended.append("append_negative_constraints")
    if appended:
        return original, True, ",".join(appended)
    return original, False, ""


def _source_plan_entry(source_plan: dict[str, Any], source_file: str) -> dict[str, Any]:
    """按 source_file 到 source_layout_plan.json 的 images[] 里找对应条目；找不到返回 {}。"""
    if not source_file:
        return {}
    for im in (source_plan.get("images") or []) if isinstance(source_plan, dict) else []:
        if isinstance(im, dict) and str(im.get("file") or "") == source_file:
            return im
    return {}


def _quote_embedded_text(embedded_text: Any, limit: int = 6) -> str:
    """把 plan_source_layout.py 算好的 embedded_text 列表格式化成可引用的 "'文字'(位置), ..." 短语。
    与 plan_source_layout.py::_quote_embedded_text 逐字同构（脚本间不耦合，各自拷贝，同一份格式约定）。"""
    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)


# "看起来像真正的 i2i 指令"特征词——同时出现在 plan_source_layout.py::_enhance_prompt 的
# _PRESERVE 模板和本文件 Tier 3 自己的 preserve 模板里，保证幂等：上一轮重建的输出、或设计 LLM
# 微调过的版本，下一轮都能被正确识别为"genuine"，不会被误判成需要重建的占位符文本。
_I2I_SIGNATURE_MARKERS = (
    "attached image",
    "attached photo",
    "reference image",
    "strict visual reference",
    "preserve its main subject",
    "preserve the real main subject",
)
_I2I_MIN_LEN = 30  # degenerate-match 防护：真正的 i2i 指令（哪怕被精修过）远长于这个下限


def _looks_like_i2i_prompt(text: str) -> bool:
    """原 prompt 是否已经读起来像真正的 image-to-image 指令（非空、非占位符、非误放的 t2i 文本）。"""
    text = str(text or "")
    if len(text.strip()) < _I2I_MIN_LEN:
        return False
    low = text.lower()
    return any(m in low for m in _I2I_SIGNATURE_MARKERS)


def _has_embedded_text_removal_clause(text: str, embedded_text: Any, limit: int = 6) -> bool:
    """text 是否已经完整包含"删除这些嵌入文字"的指令——要求含"remov"词干（真的是删除指令，
    不是提到了这段文字）且**每一条** embedded_text 的原文都以精确子串形式出现（LLM 微调的是
    措辞，不会改写要求它删除的引用文字本身，故不做模糊匹配）。"""
    items = [
        it for it in (embedded_text or [])[:limit]
        if isinstance(it, dict) and str(it.get("text") or "").strip()
    ]
    if not items:
        return False
    if "remov" not in text.lower():
        return False
    return all(str(it["text"]).strip() in text for it in items)


def _append_deltext_clause(original: str, quoted: str) -> str:
    """Tier 2：就地打补丁而非重建——在已有 prompt（可能带设计 LLM 的页面定制文字）末尾追加缺失
    的去字指令，复用 _quote_embedded_text 的引用格式，不触碰 original 其余部分。"""
    clause = (
        f" Additionally, the original image has this exact baked-in caption/title text that must be "
        f"completely REMOVED, leaving clean empty space in its place: {quoted}. Never reproduce or invent any text."
    )
    return original.rstrip(" .") + "." + clause


def _rewrite_i2i(item: dict[str, Any], source_plan: dict[str, Any], page: dict[str, Any] | None, user_request: str) -> tuple[str, bool, str]:
    original = str(item.get("prompt") or item.get("enhance_prompt") or "")
    intent = str(item.get("enhance_intent") or item.get("enhance_style") or "")
    source_file = str(item.get("source_file") or "")
    plan_entry = _source_plan_entry(source_plan, source_file)
    text_policy = str(plan_entry.get("text_policy") or "")
    embedded_text = plan_entry.get("embedded_text")
    quoted = _quote_embedded_text(embedded_text)

    # 2026-07-07 架构修复（治"规划算对了、执行没服从"这一大类问题里最隐蔽的一种）：这个函数此前
    # 对**每一条** i2i 都无条件从写死的三分支模板重新拼一遍 prompt，从不把 original（设计 LLM
    # 抄自 source_plan.enhance_prompt、且 ppt.yaml 明确授权"按 key_point 微调"过的版本）当作
    # 返回值的基础——只在最后拿 original 跟新 prompt 做字符串比较判断 changed。这意味着设计 LLM
    # 做的任何页面定制、以及 plan_source_layout.py 未来对 enhance_prompt 措辞的任何改进，全部
    # 每轮被无条件推翻重建。i2i 天然对 image_plan_lint 豁免（lint 对 mode=="image-to-image" 处处
    # 门控跳过），信任 original 的自由文本内容没有 lint 失败风险——这解除了 t2i 那种"必须重建成
    # 安全模板"的唯一理由。改为三层信任分级，统一到 _rewrite_t2i 同款"已过审就不动，只在命中
    # 具体检查失败时才动手"的哲学：
    #   Tier 1（原样保留）：original 已经像真 i2i 指令，且该有的去字引用（若 text_policy 要求）
    #     已完整存在 → 一个字都不改。
    #   Tier 2（就地打补丁）：original 可用但缺去字指令（= src_6 事故的确切场景：设计 LLM 抄来的
    #     版本本身没问题，只是漏了这一条）→ 追加缺失子句，保留其余全部定制文字。
    #   Tier 3（兜底重建，下面的逻辑原样保留）：original 缺失/不像 i2i 指令 → 走原有模板重建。
    requires_deltext = bool(quoted) and (text_policy == "remove_all_text" if ("dense" in intent or "faithful" in intent) else True)
    if original.strip() and _looks_like_i2i_prompt(original):
        if not requires_deltext or _has_embedded_text_removal_clause(original, embedded_text):
            return original, False, "kept_as_is"
        return _append_deltext_clause(original, quoted), True, "patched_missing_deltext"

    # ---- Tier 3：兜底重建（original 缺失/不可信时的安全网，逻辑与此前一致）----
    ctx = _page_context(page, user_request)
    preserve = (
        "Use the attached image as the strict visual reference. Preserve the real main subject and key factual content. "
    )
    if "dense" in intent or "faithful" in intent:
        if text_policy == "remove_all_text" and quoted:
            # 装饰性 chrome 文字（整版截图/海报自带标题/标签，非图表数据）：保结构去字，引用实抄文字。
            policy = (
                "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). "
                f"However, the original image also has this exact baked-in caption/title text that must be completely "
                f"REMOVED, leaving clean empty space in its place: {quoted}. Never reproduce or invent any text. "
                "Use contain-friendly composition."
            )
        else:
            policy = (
                "Faithfully restore clarity only; do not rewrite charts, screenshots, numbers, labels, UI structure or data. "
                "Use contain-friendly composition, no invented text."
            )
    elif "cutout" in intent or "remove_background" in intent:
        policy = (
            "Create a clean foreground cutout with transparent or plain background; remove original colored/gradient background, "
            "keep the complete subject, no cropping through devices, no new text or logo."
        )
        if quoted:
            policy += f" The original image has this exact baked-in text that must be completely removed: {quoted}."
    else:
        policy = (
            "Recompose into the target slide ratio with clean negative space for editable PPT text; remove distracting original text, "
            "do not create a collage or thumbnail grid."
        )
        if quoted:
            policy += f" Specifically, this exact baked-in text must be completely removed: {quoted}."
    # i2i 同样不拼标题/正文原句（增强图常被用作 hero/背景层，模型会把原句画成新文字；
    # 内容锚定靠 attached image 本身 + 去数字化场景名词锚即可）。
    prompt = (
        f"{preserve}{policy} Scene inspiration keywords (mood reference only — never paint any new words): "
        f"{_scene_anchor_text(ctx['anchors'])}. Source file: {source_file}. Target visual role: {intent or ctx['visual_role']}. "
        f"Text safe zone: {ctx['text_zone']}. {_style_tone(ctx)}. no new text, no logo, no letters, no watermark."
    )
    if prompt != original:
        return prompt, True, "rebuilt_fallback"
    return original, False, ""


def rewrite_plan(build: Path) -> dict[str, Any]:
    plan_path = build / "img_plan.json"
    plan = _load_json(plan_path, [])
    if not isinstance(plan, list):
        raise ValueError("img_plan.json must be an array")
    design = _load_json(build / "design.json", {})
    source_plan = _load_json(build / "source_layout_plan.json", {})
    user_request = _load_text(build / "user_request.md")
    pages = _page_map(design if isinstance(design, dict) else {})
    deck_meta = design.get("deck_meta") if isinstance(design, dict) else {}

    changed = []
    i2i_tier_counts = {"kept_as_is": 0, "patched_missing_deltext": 0, "rebuilt_fallback": 0}
    for item in plan:
        if not isinstance(item, dict):
            continue
        file_name = str(item.get("file") or "")
        page = _page_for_item(item, pages)
        mode = str(item.get("mode") or "text-to-image").lower()
        before = str(item.get("prompt") or "")
        if mode == "image-to-image":
            prompt, did_change, reason = _rewrite_i2i(item, source_plan if isinstance(source_plan, dict) else {}, page, user_request)
            if reason in i2i_tier_counts:
                i2i_tier_counts[reason] += 1
        else:
            prompt, did_change, reason = _rewrite_t2i(item, page, user_request, deck_meta)
            item["mode"] = "text-to-image"
        item["prompt"] = prompt
        if did_change:
            changed.append(
                {
                    "file": file_name,
                    "mode": item.get("mode"),
                    "reason": reason,
                    "before": before[:240],
                    "after": prompt[:360],
                }
            )

    plan_path.write_text(json.dumps(plan, ensure_ascii=False, indent=2), encoding="utf-8")
    report = {
        "changed_count": len(changed),
        "changed": changed,
        "i2i_tier_counts": i2i_tier_counts,
    }
    (build / "image_prompt_rewrite_report.json").write_text(
        json.dumps(report, ensure_ascii=False, indent=2),
        encoding="utf-8",
    )
    lines = ["# 生图提示词重写报告", "", f"- changed_count: {len(changed)}", ""]
    for entry in changed:
        lines.append(f"## {entry['file']}")
        lines.append(f"- mode: {entry['mode']}")
        lines.append(f"- reason: {entry['reason']}")
        lines.append(f"- after: {entry['after']}")
        lines.append("")
    (build / "image_prompt_rewrite_report.md").write_text("\n".join(lines).rstrip() + "\n", encoding="utf-8")
    return report


def main() -> int:
    parser = argparse.ArgumentParser(description="Rewrite PPT image prompts with page/domain/style anchors.")
    parser.add_argument("--build", default="./build", help="Build directory")
    args = parser.parse_args()
    report = rewrite_plan(Path(args.build))
    print(f"IMAGE_PROMPT_REWRITE_OK changed={report['changed_count']}")
    return 0


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