"""Build a tabletop planar linkage from the adjacent design.json (CadQuery 2.7)."""

import json
import math
import os
import re
import shutil
import struct
import xml.etree.ElementTree as ET
from itertools import combinations
from pathlib import Path
from xml.sax.saxutils import escape
from zipfile import ZIP_DEFLATED, ZipFile

import cadquery as cq
import numpy as np
from cadquery.occ_impl.exporters.svg import getSVG

HERE = Path(__file__).parent
DESIGN = json.loads((HERE / "design.json").read_text(encoding="utf-8"))
CODE = DESIGN["code"].lower()
OUT = Path(os.environ.get("ATLAS_BUILD_OUTPUT", f"{CODE}-output")).resolve()
DOWNLOAD = OUT / "downloads"
ASSETS = OUT / "assets/model"
NAME = DESIGN["name"]
VERSION = DESIGN["version"]
ROCKING = DESIGN["kind"] == "crank-rocker"
SPAN, R = DESIGN["ground_span"], DESIGN["crank_radius"]
AXES = [(0, 0), (SPAN, 0)]
if ROCKING:
    ARM_IDS = ["crank", "rocker"]
    LENGTHS = [R, DESIGN["rocker_length"]]
    BRIDGE = "coupler"
    BRIDGE_HOLES = [(0, 0), (DESIGN["coupler_length"], 0)]
else:
    assert DESIGN["kind"] == "parallel-cranks"
    AXES.append((DESIGN["third_axis_x"], DESIGN["third_axis_y"]))
    ARM_IDS = ["crank", "follower-right", "follower-rear"]
    LENGTHS = [R] * len(AXES)
    BRIDGE = "bridge"
    BRIDGE_HOLES = AXES

# All Z dimensions are measured from the underside of the base.
BASE_T, ARM_Z, T, BRIDGE_Z = 6.0, 7.2, 4.4, 20.0
PIN, BORE, END_PLAY = 7.8, 8.2, 0.4
TAIL, ARM_W = 14, 15
BOLT_D, CLEAR, HEAD_POCKET, HEAD_DEPTH = 3.0, 3.4, 6.4, 3.2
MOUNTS = [(SPAN / 3, -4), (2 * SPAN / 3, -4)]
NAMES = {
    "base": "固定底座",
    "crank": "输入曲柄",
    "rocker": "输出摇杆",
    "coupler": "双孔连杆",
    "follower-right": "右侧曲柄",
    "follower-rear": "后侧曲柄",
    "bridge": "三角连板",
    "gauge-post": "试装轴座",
    "gauge-ring": "试装孔片",
}
NOTES = {
    "base": "固定各转轴。底部沉孔容纳螺钉头，两个安装孔可把底座固定在板上。",
    "crank": "拨动橙色曲柄的尾端，另一端的偏心销带着上层连件运动。",
    "rocker": "长臂绕右侧固定轴来回摆，尾孔可装轻质指针。",
    "coupler": "两端分别套住曲柄销和摇杆销，靠固定孔距传递推拉。",
    "follower-right": "绕右侧固定轴旋转，与橙色输入曲柄保持同一方向。",
    "follower-rear": "绕后侧固定轴旋转。三个曲柄共同约束上层连板的朝向。",
    "bridge": "三个孔套住三根偏心销。观察中间的三角窗，它随连板平移。",
}
COLORS = {
    "base": "#b7c3bd",
    "crank": "#df8a44",
    "rocker": "#297679",
    "coupler": "#dfba78",
    "follower-right": "#2f7e84",
    "follower-rear": "#599b88",
    "bridge": "#dfba78",
}
PART_IDS = ["base", *ARM_IDS, BRIDGE]
GAUGES = ["gauge-post", "gauge-ring"]
BOM = [
    {"name": "M3×16 圆柱头内六角螺钉（固定轴）", "qty": len(AXES)},
    {"name": "M3×20 圆柱头内六角螺钉（偏心销）", "qty": len(AXES)},
    {"name": "M3 加大平垫圈（外径 12 mm，厚 1 mm）", "qty": 2 * len(AXES)},
    {"name": "M3 尼龙防松螺母（高约 4 mm）", "qty": 2 * len(AXES)},
]


def cylinder(xy, diameter, height, z=0):
    return cq.Solid.makeCylinder(diameter / 2, height, (*xy, z))


def capsule(a, b, width, thickness):
    dx, dy = b[0] - a[0], b[1] - a[1]
    return (
        cq.Workplane("XY")
        .center((a[0] + b[0]) / 2, (a[1] + b[1]) / 2)
        .slot2D(math.hypot(dx, dy) + width, width, math.degrees(math.atan2(dy, dx)))
        .extrude(thickness)
        .val()
    )


def frame(points, margin, inner_margin, thickness):
    if len(points) == 2:
        return capsule(*points, 2 * margin, thickness)

    def offset(distance):
        return cq.Workplane("XY").polyline(points).close().offset2D(distance).extrude(thickness).val()

    return offset(margin).cut(offset(-inner_margin))


def journal(body, xy, top, bearing_z):
    """Add a shoulder that carries the washer, then drill the bolt channel from below."""
    end = bearing_z + T + END_PLAY
    body = body.fuse(
        cylinder(xy, 12, bearing_z - top, top), cylinder(xy, PIN, end - bearing_z, bearing_z)
    )
    return body.cut(cylinder(xy, CLEAR, end), cylinder(xy, HEAD_POCKET, HEAD_DEPTH))


def geometry():
    base = frame(AXES, 14, 5, BASE_T)
    for xy in AXES:
        base = journal(base, xy, BASE_T, ARM_Z)
    for xy in MOUNTS:
        base = base.cut(cylinder(xy, 4.4, BASE_T))
    parts = {"base": base}
    for part, length in zip(ARM_IDS, LENGTHS):
        arm = capsule((-TAIL, 0), (length, 0), ARM_W, T)
        arm = arm.cut(cylinder((0, 0), BORE, T), cylinder((-TAIL, 0), CLEAR, T))
        parts[part] = journal(arm, (length, 0), T, BRIDGE_Z - ARM_Z)
    bridge = frame(BRIDGE_HOLES, 7, 5, T)
    for xy in BRIDGE_HOLES:
        bridge = bridge.cut(cylinder(xy, BORE, T))
    parts[BRIDGE] = bridge
    parts["gauge-post"] = journal(cylinder((0, 0), 18, BASE_T), (0, 0), BASE_T, ARM_Z)
    parts["gauge-ring"] = cylinder((0, 0), 16, T).cut(cylinder((0, 0), BORE, T))
    for key, shape in parts.items():
        solids = shape.clean().Solids()
        if len(solids) != 1:
            raise ValueError(f"{key} 应为一件连通的打印实体")
        parts[key] = solids[0]
    return parts


def transforms(input_deg):
    """Close the upper linkage branch using the angle of the two-pin coupler."""
    angle = math.radians(input_deg)
    tip = (R * math.cos(angle), R * math.sin(angle))
    rotations = [angle] * len(AXES)
    bridge_angle = 0.0
    if ROCKING:
        dx, dy = SPAN - tip[0], -tip[1]
        d = math.hypot(dx, dy)
        length, rocker = DESIGN["coupler_length"], LENGTHS[1]
        assert abs(length - rocker) < d < length + rocker, "该杆长组合不能连续转一整圈"
        bridge_angle = math.atan2(dy, dx) + math.acos(
            (d * d + length * length - rocker * rocker) / (2 * d * length)
        )
        bx, by = tip[0] + length * math.cos(bridge_angle), tip[1] + length * math.sin(bridge_angle)
        rotations[1] = math.atan2(by, bx - SPAN)
    result = {"base": ([0, 0, 0], 0)}
    result.update(
        {key: ([*axis, ARM_Z], rotation) for key, axis, rotation in zip(ARM_IDS, AXES, rotations)}
    )
    result[BRIDGE] = ([*tip, BRIDGE_Z], bridge_angle)
    return result


def locations(pose):
    return {
        key: cq.Location(tuple(position), (0, 0, 1), math.degrees(angle))
        for key, (position, angle) in pose.items()
    }


def fastener(length, washer_z):
    # The origin is at the bolt head's bearing face. Threads are represented by their nominal envelope.
    bolt = cylinder((0, 0), 5.5, 3, -3).fuse(cylinder((0, 0), BOLT_D, length))
    washer = cylinder((0, 0), 12, 1, washer_z).cut(cylinder((0, 0), 3.2, 1, washer_z))
    nut = cq.Workplane("XY").polygon(6, 5.5 / math.cos(math.pi / 6)).extrude(4).val()
    nut = nut.cut(cylinder((0, 0), BOLT_D, 4)).translate((0, 0, washer_z + 1))
    assert length >= washer_z + 1 + 4 + 0.5, "螺钉未穿过防松螺母"
    return cq.Compound.makeCompound([bolt, washer, nut])


def hardware():
    rows = []
    for key, xy, length in zip(ARM_IDS, AXES, LENGTHS):
        for parent, center, bolt, washer_z in [
            ("base", xy, 16, ARM_Z + T + END_PLAY),
            (key, (length, 0), 20, BRIDGE_Z - ARM_Z + T + END_PLAY),
        ]:
            ident = "axis-" + key if parent == "base" else "pin-" + key
            pos = [*center, HEAD_DEPTH]
            visual = dict(
                id=ident,
                name="M3 轴心螺钉",
                parentPartId=parent,
                frame="partLocal",
                position=pos,
                diameter=BOLT_D,
                length=bolt,
                headDiameter=5.5,
                headHeight=3,
            )
            rows.append((visual, fastener(bolt, washer_z - HEAD_DEPTH).translate(pos)))
    return rows


def rim(shape, xy, diameter, z):
    """Read the center of a machined circular feature from the actual B-rep."""
    for edge in shape.Edges():
        if edge.geomType() == "CIRCLE" and abs(2 * edge.radius() - diameter) < 1e-5:
            center = edge.arcCenter()
            if math.dist(center.toTuple(), (*xy, z)) < 1e-5:
                return cq.Vertex.makeVertex(*center.toTuple())
    raise ValueError(f"模型中找不到圆孔/轴颈 {xy}, Ø{diameter}, Z={z}")


def mesh_record(solid, stl):
    data = stl.read_bytes()
    count = struct.unpack_from("<I", data, 80)[0]
    assert len(data) == 84 + 50 * count
    dtype = [("normal", "<f4", 3), ("corners", "<f4", (3, 3)), ("attribute", "<u2")]
    triangles = np.frombuffer(data, dtype=dtype, offset=84)["corners"].astype(float)
    vertices, ids = np.unique(triangles.reshape(-1, 3), axis=0, return_inverse=True)
    faces = ids.reshape(-1, 3)
    edges = np.concatenate([faces[:, [0, 1]], faces[:, [1, 2]], faces[:, [2, 0]]])
    _, counts = np.unique(np.sort(edges, axis=1), axis=0, return_counts=True)
    a, b, c = triangles.transpose(1, 0, 2)
    volume = float(np.einsum("ij,ij->", a, np.cross(b, c)) / 6)
    record = dict(
        valid=solid.isValid(),
        volume_mm3=round(solid.Volume(), 4),
        meshVolume_mm3=round(volume, 4),
        meshWatertight=bool(np.all(counts == 2)),
        meshConsistentWinding=len(np.unique(edges, axis=0)) == len(edges),
        meshDegenerateTriangles=int(np.sum(np.linalg.norm(np.cross(b - a, c - a), axis=1) < 1e-10)),
        triangles=count,
    )
    assert (
        len(solid.Solids()) == 1
        and record["valid"]
        and record["meshWatertight"]
        and record["meshConsistentWinding"]
    )
    assert (
        not record["meshDegenerateTriangles"]
        and abs(volume / solid.Volume() - 1) < 0.01
        and abs(vertices[:, 2].min()) < 1e-6
    )
    return record


def inspect_motion(parts, bolts):
    base_pins = [rim(parts["base"], xy, PIN, ARM_Z + T + END_PLAY) for xy in AXES]
    arms = [
        (
            rim(parts[key], (0, 0), BORE, 0),
            rim(parts[key], (length, 0), PIN, BRIDGE_Z - ARM_Z + T + END_PLAY),
        )
        for key, length in zip(ARM_IDS, LENGTHS)
    ]
    bridge_bores = [rim(parts[BRIDGE], xy, BORE, 0) for xy in BRIDGE_HOLES]
    references, hits, outputs = [], [], []
    max_error = 0.0
    for deg in range(361):
        pose = transforms(deg)
        loc = locations(pose)
        measured = {}
        for key, axis, (root, tip), hole in zip(ARM_IDS, base_pins, arms, bridge_bores):
            a, b = (v.moved(loc[key]).Center() for v in (root, tip))
            h = hole.moved(loc[BRIDGE]).Center()
            max_error = max(
                max_error,
                math.hypot(a.x - axis.Center().x, a.y - axis.Center().y),
                math.hypot(b.x - h.x, b.y - h.y),
            )
            measured[key] = dict(position=[a.x, a.y, a.z], rotationZ=math.atan2(b.y - a.y, b.x - a.x))
        a, b = (v.moved(loc[BRIDGE]).Center() for v in bridge_bores[:2])
        measured[BRIDGE] = dict(position=[a.x, a.y, a.z], rotationZ=math.atan2(b.y - a.y, b.x - a.x))
        output = math.degrees(measured[ARM_IDS[1]]["rotationZ"])
        if not ROCKING:
            output += 360 * round((deg - output) / 360)
        outputs.append(output)
        if deg in (0, 37, 90, 147, 180, 251, 270, 319, 360):
            references.append(dict(input=deg, output=output, transforms=measured))
        if deg % 15 == 0:
            assembly = {k: parts[k].moved(loc[k]) for k in PART_IDS}
            assembly.update({v["id"]: s.moved(loc[v["parentPartId"]]) for v, s in bolts})
            boxes = {k: s.BoundingBox() for k, s in assembly.items()}
            for one, two in combinations(assembly, 2):
                a, b = boxes[one], boxes[two]
                if any(
                    min(getattr(a, k + "max"), getattr(b, k + "max"))
                    - max(getattr(a, k + "min"), getattr(b, k + "min"))
                    < 1e-5
                    for k in "xyz"
                ):
                    continue
                common = assembly[one].intersect(assembly[two])
                if sum(s.Volume() for s in common.Solids()) > 1e-5:
                    hits.append([deg, one, two])
    assert max_error < 1e-6 and not hits, (max_error, hits[:8])
    return dict(
        samples=361,
        solidSamples=25,
        intersections=hits,
        maxPivotError_mm=max_error,
        minimumOutput_deg=min(outputs),
        maximumOutput_deg=max(outputs),
        referencePoses=references,
    )


def parameters():
    result = {key: v for key, v in DESIGN.items() if type(v) in (int, float)}
    result.update(
        arm_z=ARM_Z,
        bridge_z=BRIDGE_Z,
        pin_diameter=PIN,
        bore_diameter=BORE,
        axial_clearance=END_PLAY,
        output_count=len(AXES) - 1,
    )
    if ROCKING:
        # At the output reversals the crank and coupler are collinear.
        def limit(distance):
            return math.acos((distance**2 - SPAN**2 - LENGTHS[1] ** 2) / (2 * SPAN * LENGTHS[1]))

        a, b = (limit(DESIGN["coupler_length"] + sign * R) for sign in (-1, 1))
        result["sweep_deg"] = round(math.degrees(abs(a - b)), 2)
    return result


def manifest(bolts):
    pose = transforms(DESIGN["default_angle_deg"])
    parts = []
    for key in PART_IDS:
        role = {"base": "fixed", "crank": "driver", BRIDGE: "coupler"}.get(key, "driven")
        if key == "base":
            offset = [0, 0, 0]
        elif key == BRIDGE:
            offset = [0, 0, 52]
        else:
            offset = [0, 0, 24]
        parts.append(
            dict(
                id=key,
                name=NAMES[key],
                role=role,
                color=COLORS[key],
                position=pose[key][0],
                explosionOffset=offset,
                description=NOTES[key],
                printable=True,
                qty=1,
                stl=f"downloads/stl/{key}.stl",
                step=f"downloads/step/{key}.step",
            )
        )
    sheets = [
        ("assembly", "连杆装配图"),
        *((k, NAMES[k] + "零件图") for k in PART_IDS),
        ("calibration", "轴孔试配图"),
    ]
    files = [
        ("print-package", "完整打印与装配包", f"{CODE}-print-package.zip"),
        ("step", "STEP 装配模型", f"{CODE}-assembly.step"),
        ("readme", "中文打印与装配说明", "README-zh.txt"),
        ("drawings", "全套二维图纸", f"{CODE}-drawings.zip"),
        ("source", "CAD 生成器（搭配设计参数）", "build.py"),
        ("design", "CAD 设计参数", "design.json"),
        ("calibration", "轴孔校准件", f"{CODE}-calibration.zip"),
    ]
    return dict(
        id=CODE,
        name=NAME,
        version=VERSION,
        units="mm",
        status="pending-physical-test",
        statusLabel="待实物试装",
        original=True,
        parameters=parameters(),
        parts=parts,
        hardwareBOM=BOM,
        visualHardware=[v for v, _ in bolts],
        references=[DESIGN["source"]],
        downloads=[dict(id=k, label=n, path="downloads/" + f) for k, n, f in files],
        drawings=[
            dict(
                id=k,
                title=n,
                path=f"assets/model/drawings/{k}.svg",
                units="mm",
                format="SVG",
                paper="A4",
                static=True,
            )
            for k, n in sheets
        ],
        calibration=dict(
            name="轴孔试配件",
            path=f"downloads/{CODE}-calibration.zip",
            parts=[dict(id=k, name=NAMES[k], path=f"downloads/stl/{k}.stl") for k in GAUGES],
        ),
        readme="downloads/README-zh.txt",
        printZip=f"downloads/{CODE}-print-package.zip",
        validation=dict(
            physicalTested=False,
            path="downloads/validation.json",
            note="已用 CAD 逐度核对一整圈的轴孔对中，每 15° 检查一次打印件与五金的实体干涉。待打印后确认实际松紧。",
        ),
    )


def projection(shape, scale, x, y, width, height):
    # Use the drawing's CAD outlines including through holes and counterbores.
    svg = ET.fromstring(
        getSVG(
            shape,
            dict(
                width=width,
                height=height,
                marginLeft=6,
                marginTop=5,
                projectionDir=(0, 0, 1),
                showAxes=False,
                showHidden=True,
                strokeWidth=0.25,
                hiddenColor=(149, 154, 151),
            ),
        )
    )
    svg.set("x", str(x))
    svg.set("y", str(y))
    bounds = shape.BoundingBox()
    center_x = (bounds.xmin + bounds.xmax) / 2
    center_y = (bounds.ymin + bounds.ymax) / 2
    group = svg.find("{http://www.w3.org/2000/svg}g")
    group.set(
        "transform",
        f"translate({width / 2:g} {height / 2:g}) scale({scale:g} {-scale:g}) translate({-center_x:g} {-center_y:g})",
    )
    group.set("stroke-width", str(0.28 / scale))
    # The CAD exporter writes full floating-point coordinates. Keep 0.001 mm on the drawing.
    for path in svg.iter("{http://www.w3.org/2000/svg}path"):
        path.set(
            "d",
            re.sub(
                r"-?\d+(?:\.\d+)?(?:e[+-]?\d+)?",
                lambda m: f"{float(m[0]):.3f}".rstrip("0").rstrip("."),
                path.get("d", ""),
                flags=re.IGNORECASE,
            ),
        )
    return ET.tostring(svg, encoding="unicode")


def sheet_notes(key):
    if key == "assembly":
        return [
            ("固定轴 / 偏心销", f"M3×16 / M3×20，各 {len(AXES)} 套"),
            ("底座上表面", f"Z = {BASE_T:g}"),
            ("下层曲柄底面", f"Z = {ARM_Z:g}"),
            ("上层连件底面", f"Z = {BRIDGE_Z:g}"),
            ("两层板厚", f"各 {T:g}"),
            ("轴向自由间隙", f"{END_PLAY:g}，垫圈压在轴肩顶面"),
        ]
    if key == "base":
        return [
            ("俯视坐标原点", "输入轴心；右向为 +X，后向为 +Y"),
            ("固定轴心 (X, Y)", "  /  ".join(f"({x:g}, {y:g})" for x, y in AXES)),
            ("底板 / 轴台", f"板厚 {BASE_T:g}；Ø12 轴台高 {ARM_Z - BASE_T:g}"),
            ("固定轴颈", f"Ø{PIN:g} × {T + END_PLAY:g}"),
            ("螺钉通孔 / 底部沉孔", f"Ø{CLEAR:g} / Ø{HEAD_POCKET:g} 深 {HEAD_DEPTH:g}"),
            ("安装孔 Ø4.4（X, Y）", "  /  ".join(f"({x:.2f}, {y:g})" for x, y in MOUNTS)),
        ]
    if key in ARM_IDS:
        index = ARM_IDS.index(key)
        return [
            ("轴孔至偏心销中心", f"{LENGTHS[index]:g}"),
            ("尾孔至轴孔中心", f"{TAIL:g}，尾孔 Ø{CLEAR:g}"),
            ("曲柄宽 × 厚", f"{ARM_W:g} × {T:g}；轴孔 Ø{BORE:g}"),
            ("偏心销台", f"Ø12，伸出臂面 {BRIDGE_Z - ARM_Z - T:g}"),
            ("偏心销颈", f"Ø{PIN:g} × {T + END_PLAY:g}"),
            ("销心螺钉孔 / 底部沉孔", f"Ø{CLEAR:g} / Ø{HEAD_POCKET:g} 深 {HEAD_DEPTH:g}"),
        ]
    if key == BRIDGE:
        return [
            ("孔心坐标 (X, Y)", "  /  ".join(f"({x:g}, {y:g})" for x, y in BRIDGE_HOLES)),
            ("销孔", f"{len(AXES)} × Ø{BORE:g} 通孔"),
            ("板厚", f"{T:g}"),
            ("外轮廓", "距孔心连线向外 7，端部 R7"),
            ("中部", "双孔间为实心连杆" if ROCKING else "三角窗边缘距孔心连线向内 5"),
        ]
    return [
        ("试装轴座", f"底片 Ø18 × {BASE_T:g}"),
        ("轴颈 / 孔片", f"Ø{PIN:g} / Ø{BORE:g}"),
        ("孔片", f"外径 16，厚 {T:g}"),
        ("螺钉", "M3×16，一套垫圈和防松螺母"),
        ("检查", "压住轴座，孔片应能用手轻轻转动"),
    ]


def make_sheets(parts, model, assembly):
    ET.register_namespace("", "http://www.w3.org/2000/svg")
    for sheet in model["drawings"]:
        key = sheet["id"]
        shape = assembly if key == "assembly" else parts.get(key)
        if key == "calibration":
            shape = cq.Compound.makeCompound(
                [parts["gauge-post"], parts["gauge-ring"].translate((25, 0, 0))]
            )
        content = [
            '<svg xmlns="http://www.w3.org/2000/svg" width="297mm" height="210mm" viewBox="0 0 297 210" role="img">',
            f"<title>{NAME} · {sheet['title']}</title>",
            '<rect width="297" height="210" fill="white"/><g font-family="sans-serif" fill="#1e302d">',
            '<path d="M8 22H289M8 191H289M187 28V185" stroke="#87958e" stroke-width=".35"/>',
        ]

        def label(x, y, value, size=3.4):
            content.append(f'<text x="{x}" y="{y}" font-size="{size}">{escape(str(value))}</text>')

        label(10, 16, sheet["title"], 5.9)
        label(220, 15, f"{DESIGN['code']}   ·   v{VERSION}")
        label(12, 32, "俯视")
        bounds = shape.BoundingBox()
        scale = min(156 / bounds.xlen, 72 / bounds.ylen, 44 / bounds.zlen)
        content.append(projection(shape, scale, 11, 35, 168, 82))
        label(12, 127, "正视")
        # Rotate the solid so that both orthographic views share a horizontal X datum.
        front = shape.rotate((0, 0, 0), (1, 0, 0), -90)
        content.append(projection(front, scale, 11, 131, 168, 54))
        label(193, 33, "装配标注" if key == "assembly" else "加工标注", 4.5)
        for i, (name, value) in enumerate(sheet_notes(key)):
            label(193, 48 + 21 * i, name, 3.1)
            label(193, 55 + 21 * i, value, 3.6)
        label(11, 200, f"机巧   /   {NAME}")
        label(207, 200, "单位 mm    ·    A4    ·    待实物试装")
        content.append("</g></svg>")
        (OUT / sheet["path"]).write_text("\n".join(content), encoding="utf-8")


def instructions():
    names = "、".join(NAMES[k] for k in PART_IDS)
    extra = (
        f"装在轴距 {SPAN:g} mm 的两个固定轴上。短曲柄孔距 {R:g} mm，摇杆孔距 {LENGTHS[1]:g} mm。"
        f"按装配图选摇杆端朝底座后侧的支路，两偏心销用孔距 {DESIGN['coupler_length']:g} mm 的连杆连接。"
        if ROCKING
        else f"在三个底座轴上各装一根半径 {R:g} mm 的曲柄。三根朝向完全相同时，三角连板才能同时套入三根偏心销。"
    )
    return (
        f"""{DESIGN["code"]}  {NAME}  v{VERSION}    单位 mm

动作来源
{DESIGN["adaptation"]}
{DESIGN["source"]["title"]}
{DESIGN["source"]["url"]}

需要打印
{names}，各 1 件。实物试装待完成。
先印 gauge-post.stl 与 gauge-ring.stl，配上一套固定轴五金试转。两件还原正式模型的轴径、孔径和轴肩高度。
建议以 PLA、0.4 mm 喷嘴、0.2 mm 层高为起点，平底朝下打印。去除孔口毛刺；试片装好后应能自由旋转。
孔比轴大 {BORE - PIN:.1f} mm（直径差）。若试片发紧，先校正首层和孔尺寸，再打印整套。

五金清单
"""
        + "\n".join(f"{h['name']} × {h['qty']}" for h in BOM)
        + f"""

装配
1. 从底座底面穿入 M3×16 螺钉，头部落入沉孔。先从每根曲柄偏心销的底面穿入 M3×20 螺钉。
2. 把各臂的大孔套在固定轴颈上。各固定轴先放平垫圈、拧上防松螺母。
3. {extra} 各偏心销顶端也加垫圈和防松螺母。垫圈落在轴颈端面，与转动件之间保留 {END_PLAY:g} mm 名义余量。
4. 按住底座，轻拨输入曲柄走一整圈。遇到阻滞就停下，逐个检查孔轴配合、垫圈和支路。底座两个 Ø4.4 安装孔可用于固定样板。

数字检查
validation.json 记录实体与 STL 检查、361 次姿态核对及每 15° 的打印件和简化五金干涉检查。
打印材料变形、真实摩擦、承载能力和使用寿命尚待实测。

文件
stl/ 为打印件，step/ 为可编辑零件。装配 STEP 含简化螺钉、垫圈、螺母；图纸在 drawings/。
将 build.py 与 design.json 放在同一目录，用 Python 3.11、CadQuery 2.7.0 和 NumPy 运行 python build.py。
默认写入 {CODE}-output/，也可用 ATLAS_BUILD_OUTPUT 指定输出目录。
"""
    )


def write_json(path, data):
    path.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")


def archive(path, members):
    with ZipFile(path, "w", ZIP_DEFLATED) as output:
        for name, source in sorted(members.items()):
            output.write(source, name)


def export_release(drawings_only=False):
    import hashlib
    from io import BytesIO

    for path in (DOWNLOAD / "stl", DOWNLOAD / "step", ASSETS / "drawings"):
        path.mkdir(parents=True, exist_ok=True)
    parts, bolts = geometry(), hardware()
    model = manifest(bolts)
    loc = locations(transforms(DESIGN["default_angle_deg"]))
    assembly = cq.Assembly(name=DESIGN["code"])
    for key in PART_IDS:
        assembly.add(parts[key], name=key, loc=loc[key], color=cq.Color(COLORS[key]))
    for item, solid in bolts:
        assembly.add(solid, name=item["id"], loc=loc[item["parentPartId"]], color=cq.Color("gray"))
    stack = assembly.toCompound()
    drawing_geometries = {**parts, "assembly": stack}

    def brep_digest(shape):
        buffer = BytesIO()
        shape.exportBrep(buffer)
        return hashlib.sha256(buffer.getvalue()).hexdigest()

    signatures = {k: brep_digest(s) for k, s in drawing_geometries.items()}
    report_path = DOWNLOAD / "validation.json"
    print(f"{DESIGN['code']}：已生成 {len(PART_IDS)} 件装配实体，开始核对运动。", flush=True)
    geometry_files = [DOWNLOAD / "stl" / (k + ".stl") for k in parts]
    geometry_files += [DOWNLOAD / "step" / (k + ".step") for k in PART_IDS]
    assembly_file = DOWNLOAD / f"{CODE}-assembly.step"
    geometry_files.append(assembly_file)

    def file_hashes():
        return {
            p.relative_to(OUT).as_posix(): hashlib.sha256(p.read_bytes()).hexdigest()
            for p in geometry_files
        }

    if drawings_only:
        previous = json.loads(report_path.read_text())
        if signatures != previous["brepSha256"] or file_hashes() != previous["geometryFiles"]:
            raise ValueError("几何或装配已改变，请完整重建模型")
    else:
        for key, solid in parts.items():
            solid.exportStl(
                str(DOWNLOAD / "stl" / (key + ".stl")), tolerance=0.07, angularTolerance=0.18
            )
        for key in PART_IDS:
            cq.exporters.export(parts[key], str(DOWNLOAD / "step" / (key + ".step")))
        assembly.export(str(assembly_file))
    report = dict(
        version=VERSION,
        physicalTested=False,
        brepSha256=signatures,
        geometryFiles=file_hashes(),
        parts={k: mesh_record(s, DOWNLOAD / "stl" / (k + ".stl")) for k, s in parts.items()},
        motion=inspect_motion(parts, bolts),
    )
    make_sheets(parts, model, stack)
    write_json(ASSETS / "mechanism.json", model)
    write_json(report_path, report)
    readme = DOWNLOAD / "README-zh.txt"
    readme.write_text(instructions(), encoding="utf-8")
    for name in ("build.py", "design.json"):
        source = Path(__file__) if name == "build.py" else HERE / name
        if source.resolve() != (DOWNLOAD / name).resolve():
            shutil.copyfile(source, DOWNLOAD / name)
    drawings = {p.name: p for p in (ASSETS / "drawings").glob("*.svg")}
    archive(DOWNLOAD / f"{CODE}-drawings.zip", drawings)
    archive(
        DOWNLOAD / f"{CODE}-calibration.zip",
        {"README-zh.txt": readme, **{k + ".stl": DOWNLOAD / "stl" / (k + ".stl") for k in GAUGES}},
    )
    members = {p.relative_to(DOWNLOAD).as_posix(): p for p in geometry_files}
    members.update(
        {
            "mechanism.json": ASSETS / "mechanism.json",
            "validation.json": report_path,
            "README-zh.txt": readme,
            "build.py": DOWNLOAD / "build.py",
            "design.json": DOWNLOAD / "design.json",
        }
    )
    members.update({"drawings/" + n: p for n, p in drawings.items()})
    archive(DOWNLOAD / f"{CODE}-print-package.zip", members)
    print(f"{DESIGN['code']}：运动、图纸、制作包已生成。", flush=True)


if __name__ == "__main__":
    import argparse

    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--drawings-only", action="store_true")
    export_release(parser.parse_args().drawings_only)
