#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
design_budget_check.py —— 设计文档「每页内容预算」确定性检查（ppt 工作流专用，治「内容顶出画布」）。

为什么需要
==========
真机反复出现：第一次设计出的网页，内容稍多的页（典型=目录页页数一多）把内容**顶出 1920×1080**（尤其底部）。
根因不是缺规则——`layout-composition.md §0.6` 早有「每页内容预算（archetype × 1920×1080）」——而是**设计 agent（弱模型）
对「一页装多少」没确定性概念**，读 prose 预算照样塞超。等到末端构图门 `layout_balance.py` 的【超出画布】WARNING
才发现已经晚了（还有「每页改 3 次放行」逃生口）。

本脚本把 §0.6 的预算**收成确定性检查**：读 build/design.json，逐页对照其 archetype 的「最大要点数 + 每条字数软上限」，
超标就**像 zod 报错一样指出：哪页 · 超在哪 · 建议怎么改（双列/拆页/精炼）**，让设计/评审在**便宜的 JSON 层**就解决，
不把顶出丢给末端构图门。与 source_usage_check / image_plan_lint / plan_source_layout 同哲学：可计算的决策交确定性脚本。

预算来源（单一真相源 = layout-composition.md §0.6，改那里也要同步本表）
====================================================================
archetype → 最大要点数 / 每条字数软上限：
  cover 0 / section 1 / split 5(×22) / cards 6(×卡标+说明) / metric 4 / fullbleed 3 / list 7(×28) / 其它 6(×30)

判定（advisory，不 halt——治本靠下游 review 在 design.json 层改）
================================================================
- 标题字数 > 上限（cover12/section10/其余14） → 【标题过长】… → 精简到一行（治 Office 重折行顶出）
- 要点数 > 上限           → 【要点过多】… → 改双列 / 拆两页 / 精炼合并
- 单条字数 > 软上限×1.3    → 【单条过长】… → 精炼说人话（类比/例子代替长定义）
（数量上限 + 单条字数两条已覆盖「过度塞页」全部情形——总字数超标必然由这两条之一先报，故不再单列「整页过密」冗余判定。）
退出码：0=全部在预算内（BUDGET_OK）；1=有超标（诊断用；调用方按需，不强制 halt）。只用标准库。

用法
====
    python design_budget_check.py [./build/design.json] [-v]
    （省略路径默认 ./build/design.json；恒写 ./build/design_budget_report.txt 同目录）
"""

import argparse
import json
import os
import re
import sys


# archetype → (最大要点数, 每条字数软上限)。数值同步 layout-composition.md §0.6。
BUDGET = {
    "cover": (0, 20),
    "section": (1, 24),
    "split": (5, 22),
    "cards": (6, 60),      # 每卡=卡标≤8 + 说明 2–3 行，故每条字数上限放宽
    "metric": (4, 24),
    "fullbleed": (3, 28),
    "list": (7, 28),
}
DEFAULT_BUDGET = (6, 30)
LONG_POINT_FACTOR = 1.3   # 单条字数 > 软上限×此 → 判过长（留余量，不为略超报噪声）

# ── cover/section「短前景项」豁免（治「编辑式封面/章节页放 kicker + 参数胶囊被误判要点过多」）──
# 编辑式封面/章节页（§2.2 产品详情页式）会在标题旁放少量**短前景元素**：1 个 kicker（eyebrow 短 label）
# + 2–3 个**参数胶囊/指标数字/spec**（如「99.9%」「<50ms」「10亿次」）。它们是前景装饰/数据点，
# **不是「要点列表 points」**，过去被 cover(0)/section(1) 的要点上限误判【要点过多】→ 编辑式封面报假超。
# 对策：cover/section 计要点数时先扣掉「短前景项」——
#   · 「参数胶囊/指标」= ≤8 字且含数字/百分号（数据 spec）→ 豁免 ≤3 个；
#   · 「kicker」= ≤8 字纯文字 eyebrow → 豁免 1 个；
#   只有**长要点（>8 字）**与**超量短项**才计入「要点过多」——真·堆长句（多条长要点）仍被拦。
# 保守：只对 cover/section 生效，内容页（list/cards/split…）预算【不放宽】。
SHORT_FG_ARCHETYPES = ("cover", "section")
SHORT_FG_LEN = 8           # ≤8 字才算「短前景项」（参数胶囊/指标/kicker），长句不在此列
METRIC_FG_ALLOWANCE = 3    # 参数胶囊/指标数字（含数字）豁免上限（§0.6 metric 同量级）
KICKER_ALLOWANCE = 1       # 纯文字 kicker（eyebrow）豁免上限
_METRIC_FG_RE = re.compile(r"[0-9%]")  # 含阿拉伯数字或百分号 → 视为参数胶囊/指标 spec

# 标题字数上限（治「Office 用本机字体重折行 → 长标题折两行下溢压副标题/顶出」，§0.6 封面头号事故）。
# cover 主标 ≤12（§0.6 铁律）；section 章节短标 ≤10；其余内容页 ≤14。
TITLE_LIMIT = {"cover": 12, "section": 10}
DEFAULT_TITLE_LIMIT = 14

# ── 渲染高度粗估（治「文字过多排下来顶出页底」；与计数预算互补：计数管「几条」、这里管「排下来多高」）──
# 计数预算可 BUDGET_OK 却仍顶出（真机实证 slide#5 底卡超 107px）——因为它没算渲染高度。
USABLE_H = 1080 - 104 - 150  # 可用内容高度 ≈ 826（1080 − 上下 padding 56+48 − header 带 ≈150）
LINE_H = 53  # 正文 38px × 1.4 放映级行高
CARD_CHROME = 90  # 每卡固定开销（padding + 卡标 + gap）估值
GAP_H = 24  # 行间距估值
# archetype → (每行卡数, 每卡每行字符数)；据此把 points 铺进网格、逐行取最高卡累加估高。
HEIGHT_COLS = {
    "cover": (1, 40), "section": (1, 40), "split": (2, 26),
    "cards": (2, 20), "metric": (2, 16), "fullbleed": (1, 40), "list": (2, 24),
}
DEFAULT_HEIGHT_COLS = (2, 22)


def _ceil_div(a, b):
    return -(-a // b) if b else 1


def estimate_page_height(archetype, points):
    """粗估该页内容排下来的高度（px）。保守估，只为 advisory 预警明显超高的页（避免误报把对的改错）。"""
    if not points:
        return 0
    cols, cpl = HEIGHT_COLS.get(archetype, DEFAULT_HEIGHT_COLS)
    rows = _ceil_div(len(points), cols)
    total = 0
    for r in range(rows):
        row_cards = points[r * cols:(r + 1) * cols]
        row_h = 0
        for p in row_cards:
            lines = max(1, _ceil_div(len(str(p).strip()), cpl))
            row_h = max(row_h, CARD_CHROME + lines * LINE_H)
        total += row_h
    return total + max(0, rows - 1) * GAP_H


def _as_text_list(v):
    """把 points/evidence 归一成字符串列表（容缺、容杂类型）。"""
    if not isinstance(v, list):
        return []
    out = []
    for x in v:
        if isinstance(x, str):
            out.append(x)
        elif isinstance(x, (int, float)):
            out.append(str(x))
        elif isinstance(x, dict):
            # blocks 形如 {content, render}；取 content 文本
            c = x.get("content") or x.get("text") or ""
            if isinstance(c, str):
                out.append(c)
    return out


def _page_points(page):
    """优先 points（上屏文案草案）；缺则回退 blocks 的 content。"""
    pts = _as_text_list(page.get("points"))
    if pts:
        return pts
    return _as_text_list(page.get("blocks"))


def _effective_point_count(archetype, points):
    """计「要点过多」时的**有效条数**。

    cover/section：先扣掉「短前景项」的豁免额度——参数胶囊/指标（含数字，≤8 字）豁免 ≤3 个、
    kicker（纯文字，≤8 字）豁免 1 个；只有长要点（>8 字）+ 超量短项才计入。这样编辑式封面带
    kicker + 2–3 参数胶囊不再误报【要点过多】，但真·堆长要点（多条长句）仍被拦。
    其它 archetype（内容页）原样返回 len(points)——预算【不放宽】。"""
    if archetype not in SHORT_FG_ARCHETYPES:
        return len(points)
    long_n = metric_short = plain_short = 0
    for p in points:
        s = str(p).strip()
        if len(s) > SHORT_FG_LEN:
            long_n += 1
        elif _METRIC_FG_RE.search(s):
            metric_short += 1   # 参数胶囊/指标数字（数据 spec）
        else:
            plain_short += 1    # kicker / 纯文字短前景
    return (
        long_n
        + max(0, metric_short - METRIC_FG_ALLOWANCE)
        + max(0, plain_short - KICKER_ALLOWANCE)
    )


def check_page(page):
    """对单页判预算，返回 finding 字符串列表（空=该页在预算内）。"""
    archetype = (page.get("archetype") or "").strip().lower()
    max_count, char_limit = BUDGET.get(archetype, DEFAULT_BUDGET)
    pno = page.get("page", "?")
    title = page.get("title") or ""
    label = f"页 {pno}（{archetype or '未注 archetype'}{('·' + title) if title else ''}）"
    points = _page_points(page)
    findings = []

    # ⓪ 标题过长（Office 重折行 → 长标题折两行下溢压副标题/顶出）
    title_limit = TITLE_LIMIT.get(archetype, DEFAULT_TITLE_LIMIT)
    tlen = len(title.strip())
    if tlen > title_limit:
        findings.append(
            f"【标题过长】{label} · 标题 {tlen} 字 > 上限 {title_limit} 字 → 精简到一行"
            "（Office 用本机字体会把长标题重折两行、下溢压住副标题或顶出画布）"
        )

    # ① 要点数超上限（cover/section 先扣短前景项豁免——kicker + 参数胶囊不算「要点」，见 _effective_point_count）
    eff_count = _effective_point_count(archetype, points)
    if eff_count > max_count:
        action = (
            "封面/章节页不该堆长要点 → 长句移到正文页（kicker + ≤3 参数胶囊/指标的短前景已豁免）"
            if max_count <= 1
            else ("改双列（grid-template-columns:1fr 1fr）/ 拆成两页 / 精炼合并同类项"
                  if archetype in ("list", "cards")
                  else "精炼合并 / 拆成两页 / 改更密版式")
        )
        findings.append(
            f"【要点过多】{label} · {eff_count} 条 > 上限 {max_count} 条 → {action}"
        )

    # ② 单条过长
    long_limit = int(char_limit * LONG_POINT_FACTOR)
    for i, p in enumerate(points, 1):
        n = len(p.strip())
        if n > long_limit:
            findings.append(
                f"【单条过长】{label} · 第 {i} 条 {n} 字 > 软上限 {char_limit} 字 → 精炼说人话"
                "（用类比/例子代替长定义，近似但好懂）"
            )

    # ③ 渲染高度溢出（与计数互补：内容排下来超过可用高 → 顶出页底；计数 OK 也可能高度超）
    est_h = estimate_page_height(archetype, points)
    if est_h > USABLE_H:
        findings.append(
            f"【高度溢出】{label} · 内容估高 ~{est_h}px > 可用 {USABLE_H}px（会顶出页底/下边缘）"
            " → ① 精炼文案 → ② 正文字号缩 ≤20%（主标/章节大标【不缩】）→ ③ 客户图 ≤1× 不放大 → ④ 拆成两页"
        )

    return findings


def check(design_path):
    """返回 (code, report_text)。code: 0 全在预算内 / 1 有超标 / 2 无 design.json。"""
    try:
        with open(design_path, encoding="utf-8-sig") as f:
            design = json.load(f)
    except FileNotFoundError:
        return 2, f"NO_DESIGN: {design_path} 不存在（设计步尚未产出 design.json）"
    except (OSError, json.JSONDecodeError) as exc:
        return 2, f"DESIGN_PARSE_ERROR: {design_path} 解析失败：{exc}"

    pages = design.get("pages") if isinstance(design, dict) else None
    if not isinstance(pages, list) or not pages:
        return 0, "BUDGET_OK: design.json 无 pages（空设计，跳过预算检查）"

    all_findings = []
    for page in pages:
        if isinstance(page, dict):
            all_findings.extend(check_page(page))

    if not all_findings:
        return 0, f"BUDGET_OK: {len(pages)} 页全部在 archetype 内容预算内（不会顶出画布）。"

    lines = [
        f"BUDGET_OVER: {len(all_findings)} 处超预算（治顶出根因——在 design.json 层就改掉，别等末端构图门）：",
    ]
    lines.extend("  - " + f for f in all_findings)
    lines.append(
        "修法阶梯（与构图门【超出画布】同序）：① 精炼说人话 + 图文并茂 → ② 缩字 ≤20%（仍 ≥ 放映级下限）"
        " → ③ 单列改双列/散列 → ④ 拆成两页 → ⑤ 删次要描述做取舍。**绝不缩字到 <24px、绝不硬塞顶出。**"
    )
    return 1, "\n".join(lines)


def main() -> int:
    parser = argparse.ArgumentParser(
        description="设计文档每页内容预算确定性检查（治内容顶出画布；读 design.json，advisory 不 halt）"
    )
    parser.add_argument("design", nargs="?", default="./build/design.json", help="design.json 路径（默认 ./build/design.json）")
    parser.add_argument("-v", "--verbose", action="store_true", help="（预留）打印每页明细")
    args = parser.parse_args()

    code, report = check(args.design)
    print(report)

    # 恒写报告到 design.json 同目录，供评审步 Read。
    try:
        out_dir = os.path.dirname(os.path.abspath(args.design)) or "."
        with open(os.path.join(out_dir, "design_budget_report.txt"), "w", encoding="utf-8") as f:
            f.write(report + "\n")
    except OSError:
        pass
    return code


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