"""P-005 / BRIM-017 — two-piece 1U 19-inch rack mount, mini PC + switch.
Brim (an AI agent), wake 296. Run: .venv-make/bin/python rack_gen.py
Model frame: X = width (0 = rack centre), Y = depth (0 = front face),
Z = height (0 = panel bottom). Print frame: front face on the bed (Y up).
All mm. Every number that came from outside is a top-level input."""
import json, sys
import numpy as np, trimesh
from trimesh.creation import box, cylinder

# ---- inputs -----------------------------------------------------------
PANEL_W, PANEL_H, PANEL_T = 482.6, 43.66, 4.0       # EIA-310 1U
HOLE_PITCH_X = 465.1
HOLE_Z = [6.35 - 0.395, 22.225 - 0.395, 38.1 - 0.395]  # panel is 0.395 inside the unit each edge
SLOT_W, SLOT_H = 10.0, 6.8                           # M6 / 10-32 clearance, obround
OPENING = 450.0
PC = dict(w=126.0, d=126.0, h=39.0)                  # Beelink EQ13, feet excluded
SW = dict(w=209.0, d=126.0, h=26.0)                  # ASSUMED switch: SG2008
CLR_W, CLR_H = 1.0, 0.8                              # total clearance on width / height
FLOOR = 2.0                                          # ledge thickness
LEDGE = 6.0                                          # ledge width under each device edge
WEB = 3.0                                            # full-height webs and joint flanges
POCKET = 8.0                                         # tool/nut room beside each joint flange
SEAT_Y = 132.0                                       # where the device's rear face stops
RAMP = 6.0                                           # stop wedges behind each bay corner: 6 in over 9 up
RAMP_RUN = 9.0                                       # 56 degrees from the bed; the slicer supports at 45
DEPTH = SEAT_Y + RAMP_RUN + 2.0                          # webs run this deep
TOPF_T, TOPF_D = 1.8, 12.0                           # top flange (thin, deep)
SEAM_X = -8.0                                        # the joint is NOT on the centreline
BOLT_D = 4.4                                         # M4 clearance
BOLTS_YZ = [(30.0, 9.0), (30.0, 35.0), (105.0, 9.0), (105.0, 35.0)]
BED = 256.0

def B(x0, x1, y0, y1, z0, z1):
    m = box(extents=[x1 - x0, y1 - y0, z1 - z0])
    m.apply_translation([(x0 + x1) / 2, (y0 + y1) / 2, (z0 + z1) / 2])
    return m

def slot(xc, zc):
    r = SLOT_H / 2
    c = cylinder(radius=r, height=PANEL_T + 2, sections=48)
    c.apply_transform(trimesh.transformations.rotation_matrix(np.pi / 2, [1, 0, 0]))
    a = c.copy(); a.apply_translation([xc - (SLOT_W / 2 - r), PANEL_T / 2, zc])
    b = c.copy(); b.apply_translation([xc + (SLOT_W / 2 - r), PANEL_T / 2, zc])
    mid = B(xc - (SLOT_W / 2 - r), xc + (SLOT_W / 2 - r), -1, PANEL_T + 1, zc - r, zc + r)
    return trimesh.boolean.union([a, b, mid])

def rod(y, z, d, x0=-40, x1=40):
    c = cylinder(radius=d / 2, height=x1 - x0, sections=48)
    c.apply_transform(trimesh.transformations.rotation_matrix(np.pi / 2, [0, 1, 0]))
    c.apply_translation([(x0 + x1) / 2, y, z])
    return c

def teardrop(y, z, d, x0, x1):
    """Bolt hole with a 56-degree roof toward +Y (up, when printed), so it needs no support."""
    from shapely.geometry import Polygon
    r, al = d / 2, np.radians(56.0)            # roof 56 degrees from the bed; the slicer supports at 45
    ta, tb = r * np.cos(al), r * np.sin(al)
    t = trimesh.creation.extrude_polygon(Polygon([(ta, -tb), (r / np.cos(al), 0), (ta, tb)]), x1 - x0)
    M = np.eye(4); M[:3, :3] = [[0, 0, 1], [1, 0, 0], [0, 1, 0]]; M[:3, 3] = [x0, y, z]
    t.apply_transform(M)
    return trimesh.boolean.union([rod(y, z, d, x0, x1), t])

# ---- layout along X (derived, then asserted) ----------------------------
# right half (switch): flange | pocket | web | bay | web
R_FL = (SEAM_X, SEAM_X + WEB)
R_WEB_IN = (R_FL[1] + POCKET, R_FL[1] + POCKET + WEB)
SW_BAY = (R_WEB_IN[1], R_WEB_IN[1] + SW["w"] + CLR_W)
R_WEB_OUT = (SW_BAY[1], SW_BAY[1] + WEB)
# left half (PC): web | bay | web | pocket | flange
L_FL = (SEAM_X - WEB, SEAM_X)
L_WEB_IN = (L_FL[0] - POCKET - WEB, L_FL[0] - POCKET)
PC_BAY = (L_WEB_IN[0] - PC["w"] - CLR_W, L_WEB_IN[0])
L_WEB_OUT = (PC_BAY[0] - WEB, PC_BAY[0])
L_GUS = (-OPENING / 2, -OPENING / 2 + WEB)
assert R_WEB_OUT[1] <= OPENING / 2, ("switch side overruns the rail opening", R_WEB_OUT)
assert L_WEB_OUT[0] >= -OPENING / 2, ("pc side overruns the rail opening", L_WEB_OUT)
assert PC["h"] + CLR_H + FLOOR + TOPF_T <= PANEL_H + 1e-9, "PC does not fit in 1U with this floor/roof"

def aperture(bay, dev):
    return B(bay[0], bay[1], -1, PANEL_T + 1, FLOOR, FLOOR + dev["h"] + CLR_H)

def wedge(x_face, sgn):
    """Stop wedge: grows from the web face into the bay behind the seat.
    Printed front-face-down it is a 56-degree slope, steeper than the support threshold."""
    from shapely.geometry import Polygon
    pg = Polygon([(x_face, SEAT_Y), (x_face + sgn * RAMP, SEAT_Y + RAMP_RUN),
                  (x_face + sgn * RAMP, DEPTH), (x_face, DEPTH)])
    return trimesh.creation.extrude_polygon(pg, PANEL_H)

def bay_parts(bay):
    return [B(bay[0], bay[0] + LEDGE, PANEL_T, DEPTH, 0, FLOOR),
            B(bay[1] - LEDGE, bay[1], PANEL_T, DEPTH, 0, FLOOR),
            B(bay[0], bay[1], PANEL_T, PANEL_T + TOPF_D, 0, FLOOR),      # front floor strip
            wedge(bay[0], +1), wedge(bay[1], -1)]

def webs(*xs):
    return [B(a, b, PANEL_T, DEPTH, 0, PANEL_H) for a, b in xs]

def build():
    hx = HOLE_PITCH_X / 2
    # right
    r = [B(SEAM_X, PANEL_W / 2, 0, PANEL_T, 0, PANEL_H),
         B(SEAM_X, OPENING / 2, PANEL_T, PANEL_T + TOPF_D, PANEL_H - TOPF_T, PANEL_H)]
    r += webs(R_FL, R_WEB_IN, R_WEB_OUT) + bay_parts(SW_BAY)
    right = trimesh.boolean.union(r)
    cuts = [aperture(SW_BAY, SW)] + [slot(hx, z) for z in HOLE_Z] + \
           [teardrop(y, z, BOLT_D, R_FL[0] - 1, R_FL[1] + 1) for y, z in BOLTS_YZ]
    right = trimesh.boolean.difference([right] + cuts)
    # left
    l = [B(-PANEL_W / 2, SEAM_X, 0, PANEL_T, 0, PANEL_H),
         B(-OPENING / 2, SEAM_X, PANEL_T, PANEL_T + TOPF_D, PANEL_H - TOPF_T, PANEL_H),
         B(-OPENING / 2, SEAM_X, PANEL_T, PANEL_T + TOPF_D, 0, FLOOR)]
    l += webs(L_FL, L_WEB_IN, L_WEB_OUT, L_GUS) + bay_parts(PC_BAY)
    left = trimesh.boolean.union(l)
    cuts = [aperture(PC_BAY, PC)] + [slot(-hx, z) for z in HOLE_Z] + \
           [teardrop(y, z, BOLT_D, L_FL[0] - 1, L_FL[1] + 1) for y, z in BOLTS_YZ]
    left = trimesh.boolean.difference([left] + cuts)
    return left, right

def dev_box(bay, dev, dx=0, dy=0, dz=0, grow=0.0):
    xc = (bay[0] + bay[1]) / 2
    y1 = SEAT_Y                              # rear face where the wedges begin
    return B(xc - dev["w"] / 2 - grow + dx, xc + dev["w"] / 2 + grow + dx,
             y1 - dev["d"] + dy, y1 + dy,
             FLOOR + dz - grow, FLOOR + dev["h"] + dz + grow)

def ivol(a, b):
    try:
        m = trimesh.boolean.intersection([a, b])
        return 0.0 if m.is_empty else float(abs(m.volume))
    except Exception as e:                    # an empty result can raise in some versions
        if "empty" in str(e).lower(): return 0.0
        raise

def to_print(m):
    p = m.copy()
    p.apply_transform(trimesh.transformations.rotation_matrix(-np.pi / 2, [1, 0, 0]))  # +Y -> -Z? fix below
    if p.bounds[0][2] < -1e-6 or abs(p.bounds[0][2]) > 1e-6:
        p.apply_translation([0, 0, -p.bounds[0][2]])
    p.apply_translation([-p.bounds[0][0], -p.bounds[0][1], 0])
    return p

if __name__ == "__main__":
    left, right = build()
    out, ok = [], True
    def chk(name, cond, detail=""):
        global ok
        ok = ok and bool(cond)
        out.append(f"{'PASS' if cond else 'FAIL'}  {name}  {detail}")
    eps = 1e-3
    for nm, m in (("left", left), ("right", right)):
        chk(f"{nm}: watertight", m.is_watertight)
        chk(f"{nm}: one body", len(m.split(only_watertight=False)) == 1, f"bodies={len(m.split(only_watertight=False))}")
        chk(f"{nm}: volume > 0", m.volume > 0, f"{m.volume/1000:.1f} cm3")
        e = m.extents
        chk(f"{nm}: fits {BED:.0f} bed (panel down)", e[0] <= BED and e[2] <= BED and e[1] <= BED, f"{e[0]:.1f} x {e[2]:.1f} footprint, {e[1]:.1f} tall")
    both = trimesh.util.concatenate([left, right])
    chk("pair: total width = 482.6", abs(both.extents[0] - PANEL_W) < eps, f"{both.extents[0]:.2f}")
    chk("pair: halves do not overlap", ivol(left, right) < eps)
    sh = right.copy(); sh.apply_translation([-0.2, 0, 0])
    chk("  control: right shifted 0.2 into left DOES overlap", ivol(left, sh) > 1.0, f"{ivol(left, sh):.1f} mm3")
    # ear holes: centre is air, 9 mm above/below is not all air
    hx = HOLE_PITCH_X / 2
    def probe(m, x, z, r=0.5):               # volume of a 1 mm cube of the part at (x, mid-panel, z)
        return ivol(m, B(x - r, x + r, PANEL_T / 2 - r, PANEL_T / 2 + r, z - r, z + r))
    for sx, m in ((-1, left), (1, right)):
        v = sum(probe(m, sx * hx, z) for z in HOLE_Z)
        chk(f"ear holes {'L' if sx<0 else 'R'}: three centres are air at x=±232.55", v < eps, f"{v:.3f} mm3")
        c = probe(m, sx * hx, (HOLE_Z[0] + HOLE_Z[1]) / 2)
        chk("  control: midway between two holes is plastic", c > 0.99, f"{c:.2f} mm3 of 1.00")
    # device fit
    for nm, bay, dev, m in (("PC", PC_BAY, PC, left), ("switch", SW_BAY, SW, right)):
        seat = dev_box(bay, dev)
        chk(f"{nm}: seated envelope clears the part", ivol(m, seat) < eps, f"{ivol(m, seat):.3f} mm3")
        chk(f"  control: envelope grown 1.5 mm collides", ivol(m, dev_box(bay, dev, grow=1.5)) > 1.0)
        sweep = B(seat.bounds[0][0], seat.bounds[1][0], -60, seat.bounds[1][1], seat.bounds[0][2], seat.bounds[1][2])
        chk(f"{nm}: slides in from the front without touching", ivol(m, sweep) < eps)
        chk(f"{nm}: something is UNDER it (drop 0.5 collides)", ivol(m, dev_box(bay, dev, dz=-0.5)) > 1.0, f"{ivol(m, dev_box(bay, dev, dz=-0.5)):.0f} mm3")
        bh = ivol(m, dev_box(bay, dev, dy=1.5)); chk(f"{nm}: something is BEHIND it (push back 1.5 collides)", bh > 1.0, f"{bh:.0f} mm3")
        fwd = ivol(m, dev_box(bay, dev, dy=-30.0))
        out.append(f"NOTE  {nm}: pulled 30 mm FORWARD it meets {fwd:.3f} mm3 of plastic — nothing but friction holds it in")
        # open floor under the device, as a fraction of its footprint
        open_frac = 1 - (2 * LEDGE * (SEAT_Y - PANEL_T) + (dev["w"] + CLR_W - 2 * LEDGE) * TOPF_D) / ((dev["w"] + CLR_W) * (SEAT_Y - PANEL_T))
        out.append(f"NOTE  {nm}: {open_frac*100:.0f}% of the floor under it is open")
    # joint bolts: a 4.0 rod passes both flanges, a 5.0 rod does not
    for i, (y, z) in enumerate(BOLTS_YZ):
        chk(f"bolt {i+1}: 4.0 mm rod passes both flanges", ivol(both_l := left, rod(y, z, 4.0, L_FL[0]-2, R_FL[1]+2)) < eps and ivol(right, rod(y, z, 4.0, L_FL[0]-2, R_FL[1]+2)) < eps)
    chk("  control: a 5.0 mm rod is blocked", ivol(left, rod(*BOLTS_YZ[0], 5.0, L_FL[0]-2, R_FL[1]+2)) > 0.5)
    # bolt head room: a 8 x 8 cylinder beside each flange must be air
    for nm, m, x0, x1 in (("L", left, L_FL[0] - POCKET + 0.2, L_FL[0] - 0.05), ("R", right, R_FL[1] + 0.05, R_FL[1] + POCKET - 0.2)):
        v = sum(ivol(m, rod(y, z, 8.0, x0, x1)) for y, z in BOLTS_YZ)
        chk(f"pocket {nm}: room for an 8 mm head/nut at all four bolts", v < eps, f"{v:.3f} mm3")
    # ---- sag estimate (thin chords, simply supported, uniform load) --------
    E_PETG = 2000.0                                     # MPa, a round low figure
    W = (0.52 + 0.60 + 0.30) * 9.81                    # N: PC + switch (assumed masses) + the part
    A_top, A_bot = TOPF_T * (TOPF_D + PANEL_T), FLOOR * (PANEL_T + TOPF_D)
    d = PANEL_H - (TOPF_T + FLOOR) / 2
    I = A_top * A_bot / (A_top + A_bot) * d * d
    sag = 5 * W * HOLE_PITCH_X ** 3 / (384 * E_PETG * I)
    M = W * HOLE_PITCH_X / 8
    arm = BOLTS_YZ[1][1] - BOLTS_YZ[0][1]
    out.append(f"EST   weakest section I = {I:.0f} mm4; mid-span sag {sag:.2f} mm elastic (E={E_PETG:.0f} MPa, load {W:.1f} N)")
    out.append(f"EST   joint moment {M/1000:.2f} N·m -> {M/arm/2:.0f} N per lower bolt (lever arm {arm:.0f} mm)")
    for nm, m in (("left", left), ("right", right)):
        p = m.copy()
        p.apply_transform(trimesh.transformations.rotation_matrix(np.pi / 2, [1, 0, 0]))   # front face (Y=0) down
        p.apply_translation(-p.bounds[0])
        chk(f"{nm}: print frame sits on z=0, {p.extents[0]:.1f} x {p.extents[1]:.1f} x {p.extents[2]:.1f}", abs(p.bounds[0][2]) < 1e-6 and p.is_watertight)
        p.export(f"rack_{nm}.stl")
    left.export("rack_left_modelframe.stl"); right.export("rack_right_modelframe.stl")
    print("\n".join(out)); print("ALL PASS" if ok else "SOME FAILED")
    json.dump({"ok": ok, "lines": out}, open("checks.json", "w"), indent=1)
    sys.exit(0 if ok else 1)
