#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Bounded visual quality gate for PPT HTML decks.

Hard engineering checks still fail. Product-detail visual issues are repairable
for at most N rounds; after that this script writes a residual report and lets
the workflow continue, so the workflow does not loop forever during peak model
traffic.
"""

from __future__ import annotations

import argparse
import json
import subprocess
from pathlib import Path


def _run(cmd: list[str], cwd: Path) -> tuple[int, str]:
    # 显式 UTF-8 解码子进程输出：中文 Windows 上 text=True 默认走 locale=GBK，
    # 解码子脚本的 UTF-8 中文日志会崩（UnicodeDecodeError）。errors="replace" 再兜一层，
    # 保证直接 CLI / 测试 / 非经 bash.ts 的宿主也不炸（bash.ts 已注入 PYTHONUTF8 兜底）。
    proc = subprocess.run(
        cmd,
        cwd=str(cwd),
        text=True,
        encoding="utf-8",
        errors="replace",
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
    )
    return proc.returncode, proc.stdout


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


def _errors_first(text: str, limit: int = 12000) -> str:
    """截断前先把 ERROR/FAILED/【…】缺陷行提到段首（各组内保持原顺序）。

    治真机事故（2026-07-02）：layout_balance 输出超 12000 字符时旧版 `text[-12000:]` 尾截，
    **前几页的 ERROR 被裁掉**、修复 agent 只看得到后半段 WARNING → 第 9 页标题遮挡/越界没人修。
    现在缺陷行永远在头部，截断只牺牲低价值 WARNING 尾巴。
    """
    if not text:
        return ""
    hot, cold = [], []
    for line in text.splitlines():
        is_hot = line.lstrip().startswith(("ERROR", "- 【", "【")) or "FAILED" in line
        (hot if is_hot else cold).append(line)
    return "\n".join(hot + cold)[:limit]


def _write_report(build: Path, title: str, sections: list[tuple[str, str]]) -> None:
    lines = [f"# {title}", ""]
    for name, text in sections:
        lines.append(f"## {name}")
        lines.append("")
        lines.append("```text")
        lines.append(_errors_first(text))
        lines.append("```")
        lines.append("")
    (build / "visual_quality_report.md").write_text("\n".join(lines), encoding="utf-8")


def _generated_review_log(build: Path) -> tuple[bool, str]:
    report = _load_json(build / "generated_image_review.json", {})
    if not isinstance(report, dict) or not report:
        return True, (
            "generated_image_review.json 不存在或为空；跳过生成图语义硬门"
            "（阶段7c 已按 2026-07-02 裁决屏蔽 LLM 图像复核，此为预期状态、非 bug；"
            "生成图带字风险由 image_prompt_rewrite 背景层去内容化 + image_plan_lint 确定性拦截）。"
        )
    ok = bool(report.get("ok", False))
    failed = report.get("failed") if isinstance(report.get("failed"), list) else []
    reviews = report.get("reviews") if isinstance(report.get("reviews"), list) else []
    lines = [
        f"ok={ok}",
        f"reviewed={report.get('reviewed', len(reviews))}",
        f"failed_count={report.get('failed_count', len(failed))}",
    ]
    for item in failed[:20]:
        if isinstance(item, dict):
            lines.append(f"- {item.get('file')}: {item.get('reason')}")
    for item in reviews[:20]:
        if isinstance(item, dict) and item.get("hard_error"):
            lines.append(f"- {item.get('file')}: {item.get('hard_error')} {item.get('reason')}")
            ok = False
    return ok, "\n".join(lines)


def main() -> int:
    parser = argparse.ArgumentParser(description="Run bounded visual quality checks.")
    parser.add_argument("--build", default="./build")
    parser.add_argument("--max-rounds", type=int, default=3)
    parser.add_argument("--strict-product-detail", action="store_true")
    args = parser.parse_args()

    root = Path.cwd()
    build = Path(args.build)
    build.mkdir(parents=True, exist_ok=True)
    state_path = build / "visual_quality_state.json"
    state = _load_json(state_path, {"round": 0})
    current_round = int(state.get("round") or 0) + 1
    state["round"] = current_round
    state_path.write_text(json.dumps(state, ensure_ascii=False, indent=2), encoding="utf-8")

    ok_path = build / "visual_quality_ok"
    residual_path = build / "visual_quality_residual.md"
    ok_path.unlink(missing_ok=True)

    # lint 只扫 img_plan prompt（不带 --outline）：ppt 链路里 t2i prompt 已由
    # image_prompt_rewrite.py 确定性净化（共享 lint 词表），design.visual.note 到不了生图模型，
    # 扫 note 只剩误伤面（页 note/标题含「架构/对比图」即 halt 的假阳事故）。
    # 若未来移除 image_prompt_rewrite，需恢复 --outline ./build/design.json。
    lint_cmd = [
        "python3",
        "skills/ui-design/scripts/image_plan_lint.py",
        str(build / "img_plan.json"),
        "-v",
    ]
    source_cmd = [
        "python3",
        "skills/ui-design/scripts/source_usage_check.py",
        "--build",
        str(build),
        "--require-existing-derived",
    ]
    style_cmd = [
        "python3",
        "skills/ui-design/scripts/deck_visual_style_check.py",
        str(build / "deck.html"),
        "--design",
        str(build / "design.json"),
        "--image-report",
        str(build / "image_generation_report.json"),
        "--source-plan",
        str(build / "source_layout_plan.json"),
        "-v",
    ]
    if args.strict_product_detail:
        style_cmd.append("--strict-product-detail")

    # 版式规划执行检查（2026-07-03 真机第4页事故）：contain 类客户图被 build 违规铺成整页背景。
    # Edit 可修 → 归**可修档**驱动修复轮（source_usage_check 主模式在 hard 档，违规不能混进去 halt）。
    intent_cmd = [
        "python3",
        "skills/ui-design/scripts/source_usage_check.py",
        "--build",
        str(build),
        "--layout-intent-only",
    ]

    lint_status, lint_log = _run(lint_cmd, root)
    source_status, source_log = _run(source_cmd, root)
    intent_status, intent_log = _run(intent_cmd, root)
    style_status, style_log = _run(style_cmd, root)
    generated_review_ok, generated_review_log = _generated_review_log(build)

    # 几何构图门（2026-07-02 接线升级：catastrophic-only → 全量 + --ppt-strict）：
    # 旧口径只判「内容不可见灾难」——第 9 页标题被卡遮挡 / 内容超出下边缘这类**测到了却不驱动修复**
    # （全量只在导出阶段 || true 报告态），41 个缺陷带残留放行是真机事故的直接原因。
    # 现在全量跑 + --ppt-strict（重叠去噪防追鬼 / 越界升 ERROR / 大空卡升 ERROR，见 layout_balance.py），
    # 归入**可修档**（visual_failed）驱动 repair；「内容不可见」零容忍仍由导出阶段 catastrophic 硬门兜底。
    export_dir = build / "export"
    geometry_status = 0
    if (export_dir / "layout-report.json").exists() or (export_dir / "export-manifest.json").exists():
        geometry_cmd = [
            "python3",
            "skills/ui-design/scripts/layout_balance.py",
            str(export_dir),
            "--ppt-strict",
            "--no-occupancy",
        ]
        # source_layout_plan.json 只在有客户图版式规划时才存在（webppt 无此文件）——传入路径即可，
        # layout_balance.py 自行判空跳过，额外反查 is_dense_info 客户图渲染宽度是否达标（WARNING）。
        source_layout_plan = build / "source_layout_plan.json"
        if source_layout_plan.exists():
            geometry_cmd += ["--source-layout-plan", str(source_layout_plan)]
        geometry_status, geometry_log = _run(geometry_cmd, root)
    else:
        geometry_log = (
            "layout-report.json 不存在（应由本阶段起头的 measure-only 产出）；跳过几何复核"
            "——不阻断，但意味着本轮未做几何检查（如 chromium 缺失导致 measure 失败）。"
        )

    # 像素级文字可读性门（2026-07-02 新增）：CSS 对比度在「文字压背景图」页物理上测不准
    # （resolveBg 只拿得到页面底色）——用 measure-only --with-bg-shots 落的背景截图采真实像素。
    # 缺 PIL/缺截图时脚本响亮 SKIP 且 exit 0（fail-open），不阻断。归可修档。
    readability_status, readability_log = _run(
        [
            "python3",
            "skills/ui-design/scripts/text_readability_pixel.py",
            str(export_dir),
        ],
        root,
    )

    # SVG 图表一致性门（2026-07-02 新增）：柱高与百分比标签颠倒 / 标签装不下（slide11/19 事故）。
    # 复杂图 fail-open 跳过。归可修档。
    chart_status, chart_log = _run(
        [
            "python3",
            "skills/ui-design/scripts/chart_sanity_check.py",
            str(build / "deck.html"),
        ],
        root,
    )

    # 用户裁决（2026-07-02）：构图/视觉验证门**只吃确定性脚本信号**，LLM 图像识别裁决屏蔽——
    # generated_image_review（多模态语义复核）不再进 hard_failed（ppt.yaml 阶段14-16 已同步 when:"false"）。
    # 复核结果仍记录进报告（信息性，供人工参考/未来恢复）；恢复 = 把 `or not generated_review_ok` 加回。
    hard_failed = (
        lint_status != 0
        or source_status != 0
    )
    visual_failed = (
        style_status != 0
        or intent_status != 0
        or geometry_status != 0
        or readability_status != 0
        or chart_status != 0
    )

    report = {
        "round": current_round,
        "max_rounds": args.max_rounds,
        "hard_ok": not hard_failed,
        "visual_ok": not visual_failed,
        "ok": not hard_failed and not visual_failed,
        "accepted_with_residual": False,
        "lint_status": lint_status,
        "source_status": source_status,
        "intent_status": intent_status,
        "style_status": style_status,
        "geometry_status": geometry_status,
        "readability_status": readability_status,
        "chart_status": chart_status,
        "generated_image_review_ok": generated_review_ok,
    }
    (build / "visual_quality_report.json").write_text(
        json.dumps(report, ensure_ascii=False, indent=2),
        encoding="utf-8",
    )
    _write_report(
        build,
        f"视觉质量门第 {current_round}/{args.max_rounds} 轮",
        [
            ("image_plan_lint", lint_log),
            ("generated_image_review", generated_review_log),
            ("source_usage_check", source_log),
            ("source_layout_intent (版式规划执行)", intent_log),
            ("deck_visual_style_check", style_log),
            ("layout_balance (几何·全量 --ppt-strict)", geometry_log),
            ("text_readability_pixel (像素级文字压图可读性)", readability_log),
            ("chart_sanity_check (SVG 图表一致性)", chart_log),
        ],
    )

    if hard_failed:
        print("VISUAL_QUALITY_HARD_FAILED")
        return 1
    if not visual_failed:
        ok_path.touch()
        residual_path.unlink(missing_ok=True)
        print("VISUAL_QUALITY_OK")
        return 0
    if current_round >= args.max_rounds:
        # 达轮数**带残留放行**（落实 docstring「lets the workflow continue」与「逐页有界修复后放行」裁决）：
        # 视觉档（style/geometry）问题记录进 residual 后 touch ok 放行导出——fast（max_rounds=1）没有
        # 修复步，不放行 = 无人能修的确定性死端；best 修满轮数后同理不再空转。
        # 硬档（lint/source/生成图复核）不走这里（上面已 exit 1）；「内容不可见」灾难仍由
        # stage_export 的 layout_balance --catastrophic-only 硬门兜底，绝不因放行而出货不可见 deck。
        report["accepted_with_residual"] = True
        (build / "visual_quality_report.json").write_text(
            json.dumps(report, ensure_ascii=False, indent=2),
            encoding="utf-8",
        )
        residual_path.write_text(
            "# 视觉质量残留问题（带残留放行）\n\n"
            f"已达到最多 {args.max_rounds} 轮视觉修复，带残留放行导出。以下问题供人工复核参考；\n"
            "「内容不可见」灾难仍由导出阶段的 catastrophic 几何硬门兜底拦截。\n\n"
            + (build / "visual_quality_report.md").read_text(encoding="utf-8"),
            encoding="utf-8",
        )
        ok_path.touch()
        print("VISUAL_QUALITY_ACCEPTED_WITH_RESIDUAL")
        return 0

    print("VISUAL_QUALITY_NEEDS_REPAIR")
    return 0


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