#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
40×30×20 mm 纸盒展开图生成器（数字练习）

只生成矢量几何（SVG + PDF）并输出坐标/尺寸 JSON，运行软件级几何自检。
本脚本不进行任何实际打印、裁剪或折叠：README 与 JSON 中的"检查"均为
对矢量数据（线段/多边形/长度/拓扑）的核对，不是实体公差验证。

依赖：reportlab（PDF 矢量绘制）。见 requirements.txt。
运行：python3 generate.py   （在本目录 outputs/ 内运行）
"""
import json
import re
import xml.dom.minidom as minidom
from pathlib import Path

from reportlab import rl_config
from reportlab.lib.units import mm as RL_MM
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.cidfonts import UnicodeCIDFont
from reportlab.pdfgen import canvas as rl_canvas

# 关闭 ASCII85，仅用 FlateDecode：macOS Quartz（Preview/QuickLook）对
# ASCII85+Flate 内容流解析存在兼容性问题，会渲染成空白/透明页。
rl_config.useA85 = 0

# PDF 中文（内置 CID 字体，无需外部字体文件）
pdfmetrics.registerFont(UnicodeCIDFont("STSong-Light"))

# ---------------------------------------------------------------------------
# 参数（与 inputs/spec.json 一致）
# ---------------------------------------------------------------------------
L, W, H = 40.0, 30.0, 20.0          # 长 / 宽 / 高 (mm)
GLUE = 8.0                          # 粘贴边投影宽度 (mm)
PAPER_W, PAPER_H = 210.0, 297.0     # A4 (mm)
MARGIN = 10.0                       # 四周留白 (mm)
RULER = 100.0                       # 校准标尺长度 (mm)

# 展开图在纸面坐标系中的原点偏移（纸面坐标 = 局部坐标 + OFFSET；+Y 向下）
OFFSET = (85.0, 120.0)

# 版面（纸面坐标，+Y 向下；SVG 与 PDF 共用同一套数值）
LAYOUT = dict(
    title_y=16.0,
    sub_y=23.5,
    legend_y=33.0,          # 图例三行：33 / 40 / 47
    steps_top=62.0,         # 左列步骤标题
    dims_top=62.0,          # 右列尺寸标题
    steps_x=14.0,
    dims_x=148.0,
    ruler_y=256.0,
    disc_y=284.0,
)

# ---------------------------------------------------------------------------
# 面板定义（局部坐标 mm，+X 向右、+Y 向下）
# 每个面板为轴对齐矩形 (x0, y0, x1, y1)
# ---------------------------------------------------------------------------
FACES = [
    # id,        中文名,        显示尺寸(x,y),      x0,   y0,   x1,   y1
    ("front",   "前面",        (L, H),              0.0, -20.0, 40.0,  0.0),
    ("bottom",  "底面",        (L, W),              0.0,   0.0, 40.0, 30.0),
    ("back",    "后面",        (L, H),              0.0,  30.0, 40.0, 50.0),
    ("top",     "顶面(盖)",    (L, W),              0.0,  50.0, 40.0, 80.0),
    ("left",    "左面",        (W, H),            -20.0,   0.0,  0.0, 30.0),
    ("right",   "右面",        (W, H),             40.0,   0.0, 60.0, 30.0),
]

TABS = [
    # id,               中文名,              显示尺寸(x,y),   x0,    y0,   x1,   y1
    ("tab_left_front",  "粘贴边·左前",       (H, GLUE),     -20.0, -8.0,  0.0,  0.0),
    ("tab_left_back",   "粘贴边·左后",       (H, GLUE),     -20.0, 30.0,  0.0, 38.0),
    ("tab_right_front", "粘贴边·右前",       (H, GLUE),      40.0, -8.0, 60.0,  0.0),
    ("tab_right_back",  "粘贴边·右后",       (H, GLUE),      40.0, 30.0, 60.0, 38.0),
]


def rect_edges(x0, y0, x1, y1):
    """返回矩形的 4 条边（每条边 (side, a, b)，顺时针）。"""
    tl, tr, br, bl = (x0, y0), (x1, y0), (x1, y1), (x0, y1)
    return [("top", tl, tr), ("right", tr, br), ("bottom", br, bl), ("left", bl, tl)]


def key_edge(p, q):
    """边归一化键：方向无关，端点排序后四舍五入到 0.001mm。"""
    a = (round(p[0], 3), round(p[1], 3))
    b = (round(q[0], 3), round(q[1], 3))
    return tuple(sorted((a, b)))


def build_panels():
    """组装所有面板（面 + 粘贴边），并以共享边自动判定剪线/折线。"""
    panels = []
    for pid, name, disp, x0, y0, x1, y1 in FACES:
        panels.append(dict(id=pid, kind="face", name=name,
                           display="%s %.0f×%.0f" % (name, disp[0], disp[1]),
                           dims=[disp[0], disp[1]], x0=x0, y0=y0, x1=x1, y1=y1))
    for pid, name, disp, x0, y0, x1, y1 in TABS:
        panels.append(dict(id=pid, kind="tab", name=name,
                           display="%s %.0f×%.0f" % (name, disp[0], disp[1]),
                           dims=[disp[0], disp[1]], x0=x0, y0=y0, x1=x1, y1=y1))

    edge_map = {}
    for i, p in enumerate(panels):
        for side, a, b in rect_edges(p["x0"], p["y0"], p["x1"], p["y1"]):
            edge_map.setdefault(key_edge(a, b), []).append((i, side))

    for i, p in enumerate(panels):
        p["edges"] = []
        for side, a, b in rect_edges(p["x0"], p["y0"], p["x1"], p["y1"]):
            owners = edge_map[key_edge(a, b)]
            if len(owners) == 2:
                other = [o for o in owners if o[0] != i][0]
                etype, shared = "fold", panels[other[0]]["id"]
            else:
                etype, shared = "cut", None
            p["edges"].append(dict(side=side, a=list(a), b=list(b), type=etype, sharedWith=shared))
    return panels


def panel_corners(p):
    return {"TL": [p["x0"], p["y0"]], "TR": [p["x1"], p["y0"]],
            "BR": [p["x1"], p["y1"]], "BL": [p["x0"], p["y1"]]}


def paper_pt(p):
    return (p[0] + OFFSET[0], p[1] + OFFSET[1])


# ---------------------------------------------------------------------------
# 几何自检（软件级，非实体打印/剪折验证）
# ---------------------------------------------------------------------------
def rects_overlap_area(a, b):
    ox = max(0.0, min(a["x1"], b["x1"]) - max(a["x0"], b["x0"]))
    oy = max(0.0, min(a["y1"], b["y1"]) - max(a["y0"], b["y0"]))
    return ox * oy


def run_checks(panels):
    checks = []

    def add(name, ok, detail=""):
        checks.append(dict(check=name, pass_=bool(ok), detail=detail))

    faces = [p for p in panels if p["kind"] == "face"]
    tabs = [p for p in panels if p["kind"] == "tab"]

    add("面板总数=6面+4粘贴边=10", len(panels) == 10, "faces=%d tabs=%d" % (len(faces), len(tabs)))
    add("六个面齐全", set(p["id"] for p in faces) == {"front", "bottom", "back", "top", "left", "right"})
    add("四个粘贴边齐全", set(p["id"] for p in tabs) ==
        {"tab_left_front", "tab_left_back", "tab_right_front", "tab_right_back"})

    expect_face = {"front": (40, 20), "bottom": (40, 30), "back": (40, 20),
                   "top": (40, 30), "left": (30, 20), "right": (30, 20)}
    ok_face_dims = True
    for p in faces:
        got = sorted([abs(p["x1"] - p["x0"]), abs(p["y1"] - p["y0"])])
        want = sorted(expect_face[p["id"]])
        if got != want:
            ok_face_dims = False
            add("面尺寸-%s" % p["id"], False, "rect=%s want=%s" % (got, want))
    add("六个面尺寸与规格一致", ok_face_dims)

    ok_tab = True
    for p in tabs:
        if sorted([abs(p["x1"] - p["x0"]), abs(p["y1"] - p["y0"])]) != [8.0, 20.0]:
            ok_tab = False
            add("粘贴边尺寸-%s" % p["id"], False)
    add("粘贴边尺寸=8×20mm", ok_tab, "投影8mm×粘贴高20mm")

    ok_margin = True
    det = ""
    for p in panels:
        for cx in (p["x0"], p["x1"]):
            for cy in (p["y0"], p["y1"]):
                px, py = paper_pt((cx, cy))
                if not (MARGIN <= px <= PAPER_W - MARGIN and MARGIN <= py <= PAPER_H - MARGIN):
                    ok_margin = False
                    det = "panel=%s paper=(%.1f,%.1f)" % (p["id"], px, py)
    add("全部面板在A4四周10mm边界内", ok_margin, det)

    ok_no_overlap = True
    det = ""
    for i in range(len(panels)):
        for j in range(i + 1, len(panels)):
            area = rects_overlap_area(panels[i], panels[j])
            if area > 1e-6:
                ok_no_overlap = False
                det = "%s∩%s=%.2fmm²" % (panels[i]["id"], panels[j]["id"], area)
    add("任意两面板面积不相交(纸面不重叠)", ok_no_overlap, det)

    edge_keys = {}
    for p in panels:
        for e in p["edges"]:
            edge_keys.setdefault(key_edge(e["a"], e["b"]), []).append((p["id"], e["type"]))
    n_fold = sum(1 for k, o in edge_keys.items() if len(o) == 2)
    n_cut = sum(1 for k, o in edge_keys.items() if len(o) == 1)
    ok_cls = all((len(o) == 2) == any(t == "fold" for _, t in o) for k, o in edge_keys.items())
    add("折线恰两面板共享、剪线为外边界", ok_cls, "折线%d条 剪线%d条" % (n_fold, n_cut))
    add("折线数量=9", n_fold == 9, "实际%d" % n_fold)

    adj = {p["id"]: set() for p in panels}
    for p in panels:
        for e in p["edges"]:
            if e["sharedWith"]:
                adj[p["id"]].add(e["sharedWith"])
                adj[e["sharedWith"]].add(p["id"])
    seen = set()
    stack = [panels[0]["id"]]
    while stack:
        cur = stack.pop()
        if cur in seen:
            continue
        seen.add(cur)
        stack.extend(adj[cur] - seen)
    add("全部面板单连通(六个面连通可折)", seen == set(adj.keys()),
        "连通=%d/%d" % (len(seen), len(adj)))

    add("校准标尺=100mm", abs(RULER - 100.0) < 1e-9, "%.1fmm" % RULER)

    return checks, dict(n_fold=n_fold, n_cut=n_cut)


# ---------------------------------------------------------------------------
# SVG 生成（纸面 +Y 向下，1 用户单位 = 1mm）
# ---------------------------------------------------------------------------
SVG_FONT = "'PingFang SC','Hiragino Sans GB','Microsoft YaHei','Noto Sans CJK SC','Helvetica Neue',Arial,sans-serif"


def svg_text(x, y, s, size, anchor="middle", fill="#111", weight="normal", rotate=None):
    t = ('<text x="%.3f" y="%.3f" font-family="%s" font-size="%.3f" fill="%s" '
         'font-weight="%s" text-anchor="%s"' % (x, y, SVG_FONT, size, fill, weight, anchor))
    if rotate:
        t += ' transform="rotate(%s %.3f %.3f)"' % (rotate, x, y)
    t += ">%s</text>" % s
    return t


def build_svg(panels):
    L_ = LAYOUT
    lines = ['<?xml version="1.0" encoding="UTF-8"?>']
    lines.append('<svg xmlns="http://www.w3.org/2000/svg" width="210mm" height="297mm" viewBox="0 0 210 297">')
    lines.append('<defs>')
    lines.append('<pattern id="hatch" width="2" height="2" patternUnits="userSpaceOnUse" patternTransform="rotate(45)">')
    lines.append('<rect width="2" height="2" fill="#e3e3e3"/>')
    lines.append('<line x1="0" y1="0" x2="0" y2="2" stroke="#b9b9b9" stroke-width="0.5"/>')
    lines.append('</pattern></defs>')

    # 页面白色背景 + 留白安全区参考框
    lines.append('<rect x="0" y="0" width="210" height="297" fill="#ffffff"/>')
    lines.append('<rect x="%.1f" y="%.1f" width="%.1f" height="%.1f" fill="none" stroke="#cccccc" '
                 'stroke-width="0.15" stroke-dasharray="1.5 1.5"/>' %
                 (MARGIN, MARGIN, PAPER_W - 2 * MARGIN, PAPER_H - 2 * MARGIN))

    # 面板填充（粘贴边斜纹灰，面白色）
    for p in panels:
        x0, y0 = paper_pt((p["x0"], p["y0"]))
        x1, y1 = paper_pt((p["x1"], p["y1"]))
        fill = 'url(#hatch)' if p["kind"] == "tab" else '#ffffff'
        lines.append('<rect x="%.3f" y="%.3f" width="%.3f" height="%.3f" fill="%s" stroke="none"/>'
                     % (x0, y0, x1 - x0, y1 - y0, fill))

    # 边（去重）：折线虚线、剪线实线
    drawn = {}
    for p in panels:
        for e in p["edges"]:
            k = key_edge(e["a"], e["b"])
            if k in drawn:
                continue
            drawn[k] = True
            a, b = paper_pt(e["a"]), paper_pt(e["b"])
            if e["type"] == "fold":
                lines.append('<line x1="%.3f" y1="%.3f" x2="%.3f" y2="%.3f" stroke="#555555" '
                             'stroke-width="0.28" stroke-dasharray="2.2 1.3" stroke-linecap="round"/>'
                             % (a[0], a[1], b[0], b[1]))
            else:
                lines.append('<line x1="%.3f" y1="%.3f" x2="%.3f" y2="%.3f" stroke="#111111" '
                             'stroke-width="0.34" stroke-linecap="round" stroke-linejoin="round"/>'
                             % (a[0], a[1], b[0], b[1]))

    # 面板标签
    for p in panels:
        cx = (p["x0"] + p["x1"]) / 2.0 + OFFSET[0]
        cy = (p["y0"] + p["y1"]) / 2.0 + OFFSET[1]
        if p["kind"] == "tab":
            lines.append(svg_text(cx, cy + 0.9, "粘贴", 3.2, fill="#666"))
        else:
            wpx, hpx = p["x1"] - p["x0"], p["y1"] - p["y0"]
            lines.append(svg_text(cx, cy - 0.5, p["name"], 4.4, weight="bold"))
            lines.append(svg_text(cx, cy + 3.4, "%.0f × %.0f mm" % (max(wpx, hpx), min(wpx, hpx)), 3.4, fill="#333"))

    # 标题 / 副标题 / 图例
    lines.append(svg_text(105, L_["title_y"], "40 × 30 × 20 mm  纸盒展开图（六面连通）",
                          7.5, weight="bold"))
    lines.append(svg_text(105, L_["sub_y"], "A4 · 实线=剪开  虚线=折痕  灰色斜纹=粘贴边 · 请以 100% 实际尺寸打印",
                          3.8, fill="#333"))
    ly = L_["legend_y"]
    lines.append('<line x1="17" y1="%.1f" x2="44" y2="%.1f" stroke="#111111" stroke-width="0.6"/>' % (ly, ly))
    lines.append(svg_text(49, ly + 1, "实线 = 剪开线（cut）", 3.8, anchor="start"))
    lines.append('<line x1="17" y1="%.1f" x2="44" y2="%.1f" stroke="#555555" stroke-width="0.55" '
                 'stroke-dasharray="2.2 1.3"/>' % (ly + 7, ly + 7))
    lines.append(svg_text(49, ly + 7 + 1, "虚线 = 折叠线（fold）", 3.8, anchor="start"))
    lines.append('<rect x="17" y="%.1f" width="27" height="5" fill="url(#hatch)" stroke="#666" stroke-width="0.3"/>'
                 % (ly + 14 - 2.5))
    lines.append(svg_text(49, ly + 14 + 1, "灰色斜纹 = 粘贴边（涂胶，贴到相邻面内侧）", 3.8, anchor="start"))

    # 左列：折叠/粘贴步骤
    steps = ["折叠/粘贴步骤",
             "1. 沿实线剪下整体外轮廓。",
             "2. 沿虚线预折出 90° 折痕。",
             "3. 以底面为底，四周侧面立起。",
             "4. 四条粘贴边涂胶，贴到前/后面",
             "   内侧，粘成盒身。",
             "5. 顶面沿后侧折下盖住盒口。"]
    lines.append(svg_text(L_["steps_x"], L_["steps_top"], steps[0], 4.2, anchor="start", weight="bold"))
    for i, s in enumerate(steps[1:], 1):
        lines.append(svg_text(L_["steps_x"], L_["steps_top"] + i * 5.2, s, 3.3, anchor="start", fill="#333"))

    # 右列：尺寸说明
    dims = ["尺寸说明",
            "底面/顶面  40 × 30 mm",
            "前面/后面  40 × 20 mm",
            "左面/右面  30 × 20 mm",
            "粘贴边      20 × 8 mm ×4",
            "展开图外廓  80 × 100 mm"]
    lines.append(svg_text(L_["dims_x"], L_["dims_top"], dims[0], 4.2, anchor="start", weight="bold"))
    for i, s in enumerate(dims[1:], 1):
        lines.append(svg_text(L_["dims_x"], L_["dims_top"] + i * 5.2, s, 3.3, anchor="start", fill="#333"))

    # 校准标尺（100mm）
    rx0, rx1, ry = 55.0, 155.0, L_["ruler_y"]
    lines.append('<line x1="%.3f" y1="%.3f" x2="%.3f" y2="%.3f" stroke="#111111" stroke-width="0.5"/>'
                 % (rx0, ry, rx1, ry))
    for i in range(101):
        x = rx0 + i
        h = 6 if i % 10 == 0 else (4 if i % 5 == 0 else 2)
        lines.append('<line x1="%.3f" y1="%.3f" x2="%.3f" y2="%.3f" stroke="#111111" stroke-width="0.3"/>'
                     % (x, ry, x, ry + h))
        if i % 10 == 0:
            lines.append(svg_text(x, ry + h + 3.5, "%d" % i, 3.4))
    lines.append(svg_text((rx0 + rx1) / 2, ry + 15,
                          "校准标尺 100 mm —— 打印后请用直尺实测，长度应恰为 100 mm（100% 打印）",
                          4.2, weight="bold"))

    # 底部声明
    lines.append(svg_text(105, L_["disc_y"],
                          "数字练习件：坐标为矢量几何自检结果，未实际打印/剪折，不声称实体公差验证。",
                          3.2, fill="#777"))
    lines.append("</svg>")
    return "\n".join(lines)


# ---------------------------------------------------------------------------
# PDF 生成（reportlab 坐标/线宽/字号以「磅(pt)」为单位；此处统一用 mm 输入再换算）
#   纸面坐标 +Y 向下；reportlab 原点左下、+Y 向上。
# ---------------------------------------------------------------------------
def _pt(mm_val):
    """毫米 → 磅。"""
    return mm_val * RL_MM


def pdf_y(y):
    """纸面 +Y 向下(mm) → reportlab +Y 向上(pt)。"""
    return (PAPER_H - y) * RL_MM


def pdf_text(c, x, top_y, s, size_mm, align="center", color=(0, 0, 0)):
    font = "STSong-Light"
    c.setFont(font, _pt(size_mm))
    c.setFillColorRGB(*color)
    if align == "center":
        x_pt = _pt(x) - c.stringWidth(s, font, _pt(size_mm)) / 2.0
    else:
        x_pt = _pt(x)
    c.drawString(x_pt, pdf_y(top_y), s)


def pdf_line(c, a, b, dash=None, width_mm=0.6, color=(0.05, 0.05, 0.05)):
    c.setStrokeColorRGB(*color)
    c.setLineWidth(_pt(width_mm))
    c.setLineJoin(1)
    c.setLineCap(1)
    if dash:
        c.setDash(*dash)
    else:
        c.setDash()
    c.line(_pt(a[0]), pdf_y(a[1]), _pt(b[0]), pdf_y(b[1]))
    c.setDash()


def pdf_rect(c, x0, y0, x1, y1, fill=None, stroke=None, width_mm=0.4):
    # 输入为纸面 +Y 向下坐标(mm)
    top, bottom = y0, y1
    rl_y = pdf_y(bottom)
    w = _pt(x1 - x0)
    h = _pt(bottom - top)
    if fill is not None:
        c.setFillColorRGB(*fill)
        c.rect(_pt(x0), rl_y, w, h, stroke=0, fill=1)
    if stroke is not None:
        c.setStrokeColorRGB(*stroke)
        c.setLineWidth(_pt(width_mm))
        c.rect(_pt(x0), rl_y, w, h, stroke=1, fill=0)


def build_pdf(panels, out_path):
    L_ = LAYOUT
    c = rl_canvas.Canvas(str(out_path), pagesize=(PAPER_W * RL_MM, PAPER_H * RL_MM))

    # 整页白色背景（与 SVG 一致，避免部分查看器把透明页背景渲染成黑）
    pdf_rect(c, 0, 0, PAPER_W, PAPER_H, fill=(1, 1, 1))

    # 留白安全区参考框
    pdf_rect(c, MARGIN, MARGIN, PAPER_W - MARGIN, PAPER_H - MARGIN,
             stroke=(0.8, 0.8, 0.8), width_mm=0.15)

    # 面板填充
    for p in panels:
        x0, y0 = paper_pt((p["x0"], p["y0"]))
        x1, y1 = paper_pt((p["x1"], p["y1"]))
        pdf_rect(c, x0, y0, x1, y1, fill=(0.89, 0.89, 0.89) if p["kind"] == "tab" else (1, 1, 1))

    # 边（折线虚线、剪线实线）
    drawn = {}
    for p in panels:
        for e in p["edges"]:
            k = key_edge(e["a"], e["b"])
            if k in drawn:
                continue
            drawn[k] = True
            a, b = paper_pt(e["a"]), paper_pt(e["b"])
            if e["type"] == "fold":
                pdf_line(c, a, b, dash=(2.2, 1.3), width_mm=0.28, color=(0.33, 0.33, 0.33))
            else:
                pdf_line(c, a, b, width_mm=0.34, color=(0.05, 0.05, 0.05))

    # 面板标签
    for p in panels:
        cx = (p["x0"] + p["x1"]) / 2.0 + OFFSET[0]
        cy = (p["y0"] + p["y1"]) / 2.0 + OFFSET[1]
        if p["kind"] == "tab":
            pdf_text(c, cx, cy - 1, "粘贴", 3.2, color=(0.35, 0.35, 0.35))
        else:
            wpx, hpx = p["x1"] - p["x0"], p["y1"] - p["y0"]
            pdf_text(c, cx, cy + 0.8, p["name"], 4.4)
            pdf_text(c, cx, cy - 5.5, "%.0f × %.0f mm" % (max(wpx, hpx), min(wpx, hpx)),
                     3.4, color=(0.2, 0.2, 0.2))

    # 标题 / 副标题
    pdf_text(c, 105, L_["title_y"], "40 × 30 × 20 mm 纸盒展开图（六面连通）", 7.5)
    pdf_text(c, 105, L_["sub_y"], "A4 · 实线=剪开  虚线=折痕  灰色=粘贴边 · 请以 100% 实际尺寸打印",
             3.8, color=(0.2, 0.2, 0.2))

    # 图例
    ly = L_["legend_y"]
    pdf_line(c, (17, ly), (44, ly), width_mm=0.6, color=(0.05, 0.05, 0.05))
    pdf_text(c, 49, ly - 1.4, "实线 = 剪开线（cut）", 3.8, align="left")
    pdf_line(c, (17, ly + 7), (44, ly + 7), dash=(2.2, 1.3), width_mm=0.55, color=(0.33, 0.33, 0.33))
    pdf_text(c, 49, ly + 7 - 1.4, "虚线 = 折叠线（fold）", 3.8, align="left")
    pdf_rect(c, 17, ly + 14 - 2.5, 44, ly + 14 + 2.5, fill=(0.89, 0.89, 0.89), stroke=(0.4, 0.4, 0.4))
    pdf_text(c, 49, ly + 14 - 1.4, "灰色 = 粘贴边（涂胶，贴到相邻面内侧）", 3.8, align="left")

    # 左列步骤
    steps = ["折叠/粘贴步骤",
             "1. 沿实线剪下整体外轮廓。",
             "2. 沿虚线预折出 90° 折痕。",
             "3. 以底面为底，四周侧面立起。",
             "4. 四条粘贴边涂胶，贴到前/后面内侧。",
             "5. 顶面沿后侧折下盖住盒口。"]
    pdf_text(c, L_["steps_x"], L_["steps_top"], steps[0], 4.2, align="left")
    for i, s in enumerate(steps[1:], 1):
        pdf_text(c, L_["steps_x"], L_["steps_top"] + i * 5.2, s, 3.3, align="left", color=(0.2, 0.2, 0.2))

    # 右列尺寸
    dims = ["尺寸说明", "底面/顶面 40 × 30 mm", "前面/后面 40 × 20 mm",
            "左面/右面 30 × 20 mm", "粘贴边 20 × 8 mm ×4", "展开图外廓 80 × 100 mm"]
    pdf_text(c, L_["dims_x"], L_["dims_top"], dims[0], 4.2, align="left")
    for i, s in enumerate(dims[1:], 1):
        pdf_text(c, L_["dims_x"], L_["dims_top"] + i * 5.2, s, 3.3, align="left", color=(0.2, 0.2, 0.2))

    # 校准标尺（100mm）
    rx0, rx1, ry = 55.0, 155.0, L_["ruler_y"]
    pdf_line(c, (rx0, ry), (rx1, ry), width_mm=0.5)
    for i in range(101):
        x = rx0 + i
        h = 6 if i % 10 == 0 else (4 if i % 5 == 0 else 2)
        pdf_line(c, (x, ry), (x, ry + h), width_mm=0.3)
        if i % 10 == 0:
            pdf_text(c, x, ry + h + 3.0, "%d" % i, 3.4)
    pdf_text(c, (rx0 + rx1) / 2, ry + 15,
             "校准标尺 100 mm —— 打印后请用直尺实测，长度应恰为 100 mm（100% 打印）", 4.2)

    # 底部声明
    pdf_text(c, 105, L_["disc_y"], "数字练习件：坐标为矢量几何自检结果，未实际打印/剪折，不声称实体公差验证。",
             3.2, color=(0.45, 0.45, 0.45))
    c.showPage()
    c.save()


# ---------------------------------------------------------------------------
# JSON
# ---------------------------------------------------------------------------
def build_geometry(panels, checks, check_summary):
    def panel_dict(p):
        return dict(
            id=p["id"], kind=p["kind"], name=p["name"], display=p["display"],
            dimsMm=p["dims"],
            rectLocalMm=dict(x0=p["x0"], y0=p["y0"], x1=p["x1"], y1=p["y1"]),
            cornersLocalMm=panel_corners(p),
            cornersPaperMm={k: list(paper_pt(v)) for k, v in panel_corners(p).items()},
            areaMm2=abs(p["x1"] - p["x0"]) * abs(p["y1"] - p["y0"]),
            edges=[dict(side=e["side"], a=e["a"], b=e["b"], aPaper=list(paper_pt(e["a"])),
                        bPaper=list(paper_pt(e["b"])), type=e["type"], sharedWith=e["sharedWith"])
                   for e in p["edges"]],
        )

    faces = [panel_dict(p) for p in panels if p["kind"] == "face"]
    tabs = [panel_dict(p) for p in panels if p["kind"] == "tab"]
    xs = [p["x0"] for p in panels] + [p["x1"] for p in panels]
    ys = [p["y0"] for p in panels] + [p["y1"] for p in panels]
    return dict(
        meta=dict(title="40×30×20 mm 纸盒展开图", units="mm", generator="outputs/generate.py",
                  boxMm=dict(length=L, width=W, height=H), glueTabMm=GLUE,
                  paperMm=[PAPER_W, PAPER_H], marginMm=MARGIN, rulerMm=RULER,
                  paperOriginOffsetMm=dict(x=OFFSET[0], y=OFFSET[1]),
                  note="数字纸盒展开图练习；未实际剪折，不声称实体公差验证。检查为矢量几何/拓扑核对。"),
        faces=faces, glueTabs=tabs,
        rulerMm=dict(startPaperMm=[55.0, LAYOUT["ruler_y"]], endPaperMm=[155.0, LAYOUT["ruler_y"]],
                     lengthMm=RULER),
        boundingBoxLocalMm=dict(x0=min(xs), y0=min(ys), x1=max(xs), y1=max(ys),
                                width=max(xs) - min(xs), height=max(ys) - min(ys)),
        checks=dict(summary=check_summary, items=checks),
    )


# ---------------------------------------------------------------------------
# HTML 预览
# ---------------------------------------------------------------------------
def build_html(svg_string):
    return """<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>40×30×20 mm 纸盒展开图预览</title>
<style>
  html, body { margin: 0; padding: 0; }
  body { background: #e9edf2; font-family: -apple-system, "PingFang SC", "Microsoft YaHei", sans-serif; color:#1a1a1a; }
  header { padding: 18px 24px 10px; }
  header h1 { margin: 0 0 4px; font-size: 18px; }
  header p { margin: 2px 0; font-size: 13px; color:#444; }
  header b { color:#c0392b; }
  .toolbar { padding: 0 24px 16px; display:flex; gap:10px; flex-wrap:wrap; }
  .toolbar a, .toolbar button { display:inline-block; padding:8px 14px; border-radius:6px; border:1px solid #2f6fb7;
    background:#2f6fb7; color:#fff; text-decoration:none; font-size:13px; cursor:pointer; }
  .stage { margin: 0 auto; max-width: 900px; }
  .stage svg { display:block; width: 100%; height: auto; background:#fff; box-shadow:0 2px 12px rgba(0,0,0,.18); }

  /* 页面盒：A4、页边距 0（@page 必须写在 @media 之外） */
  @page { size: A4; margin: 0; }
  @media print {
    html, body { margin: 0; padding: 0; width: 210mm; background: #fff; }
    header, .toolbar { display: none; }
    .stage { margin: 0; max-width: none; width: 210mm; }
    .stage svg { display: block; width: 210mm; height: 297mm; box-shadow: none; }
  }
</style>
</head>
<body>
<header>
  <h1>40 × 30 × 20 mm 纸盒展开图（六面连通）</h1>
  <p>打印设置：纸张 <b>A4</b> · 缩放 <b>100%（实际大小）</b> · 页边距 <b>无（None）</b> · <b>关闭</b>页眉/页脚。</p>
  <p>打印后用直尺量下方标尺，应为 <b>100 mm</b>；若小于 100 mm 说明被缩放，请重设以上选项后再打。</p>
  <p>实线=剪开 · 虚线=折痕 · 灰色斜纹=粘贴边。</p>
</header>
<div class="toolbar">
  <a href="box.pdf" download>下载 PDF（矢量，可直接打印）</a>
  <a href="box.svg" download>下载 SVG（矢量源文件）</a>
  <a href="geometry.json" download>下载坐标/尺寸 JSON</a>
  <button onclick="window.print()">打印本页（A4 · 100% · 边距无）</button>
</div>
<div class="stage">
__SVG__
</div>
</body>
</html>
""".replace("__SVG__", svg_string)


# ---------------------------------------------------------------------------
# 版面边界扫描（额外验证 SVG 注释/文本/图形未越出 10mm 安全区）
# ---------------------------------------------------------------------------
def _inside_defs(el):
    n = el
    while n is not None:
        if n.nodeType == 1 and n.tagName in ("defs", "pattern"):
            return True
        n = n.parentNode
    return False


def scan_svg_margins(svg_text):
    doc = minidom.parseString(svg_text)
    bad = []
    for el in doc.getElementsByTagName("text"):
        if _inside_defs(el):
            continue
        x, y = float(el.getAttribute("x")), float(el.getAttribute("y"))
        if not (MARGIN <= x <= PAPER_W - MARGIN and MARGIN <= y <= PAPER_H - MARGIN):
            bad.append("text x=%.1f y=%.1f" % (x, y))
    for el in doc.getElementsByTagName("line"):
        if _inside_defs(el):
            continue
        for attr in ("x1", "y1", "x2", "y2"):
            v = float(el.getAttribute(attr))
            if attr in ("x1", "x2") and not (MARGIN <= v <= PAPER_W - MARGIN):
                bad.append("line %s=%.1f" % (attr, v))
            if attr in ("y1", "y2") and not (MARGIN <= v <= PAPER_H - MARGIN):
                bad.append("line %s=%.1f" % (attr, v))
    # rect：忽略整页白色背景与安全区边框（其 y/x 为 0 或超出，属页面辅助层）
    return bad


# ---------------------------------------------------------------------------
# main
# ---------------------------------------------------------------------------
def main():
    out_dir = Path(__file__).resolve().parent
    panels = build_panels()
    checks, check_summary = run_checks(panels)

    svg_string = build_svg(panels)
    (out_dir / "box.svg").write_text(svg_string, encoding="utf-8")

    build_pdf(panels, out_dir / "box.pdf")

    geo = build_geometry(panels, checks, check_summary)
    (out_dir / "geometry.json").write_text(
        json.dumps(geo, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")

    (out_dir / "preview.html").write_text(build_html(svg_string), encoding="utf-8")

    margin_bad = scan_svg_margins(svg_string)

    print("=" * 62)
    print("几何自检（矢量/拓扑核对，非实体剪折验证）")
    print("=" * 62)
    all_ok = True
    for ch in checks:
        mark = "PASS" if ch["pass_"] else "FAIL"
        if not ch["pass_"]:
            all_ok = False
        print("[%s] %s  %s" % (mark, ch["check"], ch["detail"]))
    print("-" * 62)
    print("折线 %d 条，剪线 %d 条" % (check_summary["n_fold"], check_summary["n_cut"]))
    print("SVG 越出10mm安全区元素: %s" % (margin_bad if margin_bad else "无"))
    if margin_bad:
        all_ok = False
    print("全部通过: %s" % all_ok)
    print("输出目录: %s" % out_dir)
    return 0 if all_ok else 1


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