"""P-007 / BRIM-019 — pull-out slide for an 8.2 L filter tank on a fridge shelf.
Brim (an AI agent), wake 300. Run: ../../.venv-make/bin/python slide_gen.py
Model frame: X = travel (0 = front of the rail, + = into the fridge),
Y = across the rail (0 = centre), Z = up (0 = shelf). All mm.
The set = 2 rails + 2 runners + 1 tie bar (rev C). The tie bar drops into a
slot at the back of both rails: it is the rear stop and it sets the spacing.
A single-rail gate with the same section is exported too.
Every number that came from outside is a top-level input."""
import json, math, sys
import numpy as np, trimesh
from shapely.geometry import Polygon
from trimesh.creation import box, cylinder, extrude_polygon

# ---- inputs -----------------------------------------------------------
TANK = dict(w=214.0, d=304.0, h=220.0, kg_full=10.0)   # maker's pages; d is the travel axis
L = 240.0            # rail and runner length (a 256 mm bed, with margin)
W = 40.0             # width of both
FLOOR = 3.0          # rail floor
CH = 8.0             # channel depth
RAIL_H = FLOOR + CH  # 11
CH_BOT = 26.0        # channel width at its floor
SLOPE = 60.0         # dovetail wall, degrees from the bed (slicer supports below 45)
INSET = CH / math.tan(math.radians(SLOPE))
CH_TOP = CH_BOT - 2 * INSET
FRONT_WALL = 8.0     # the forward stop: solid end of the channel
TRAVEL = 60.0
GATE_X0, GATE_T, GATE_W = 228.0, 4.0, 32.0             # drop-in rear stop: slot position, slot length, tab width
SLOT_Z = 5.0         # the slot crosses the whole rail above this height; the 32 mm middle goes down to the floor
SPACING = 150.0      # rail centre to rail centre, set by the tie bar
DECK = 5.0           # runner deck thickness
CLR = 0.4            # horizontal clearance, each side of the key
KEY_LIFT = 0.5       # key bottom above the channel floor
KEY_X0 = FRONT_WALL + TRAVEL
KEY_X1 = GATE_X0 - 0.5
PAD_D, PAD_DEPTH = 12.5, 0.0   # rev A had 0.6 mm locating pockets on the bed faces: the slicer wanted supports under all four (S1 wrong). Rev B: none.
PADS_X = [95.0, 215.0]
GATE_CLR = 0.3

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 prism(yz, x0, x1):
    """Extrude a (y, z) polygon along X from x0 to x1."""
    m = extrude_polygon(Polygon(yz), x1 - x0)           # (a, b, c) = (y, z, x)
    T = np.array([[0, 0, 1, x0], [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1.0]])
    m.apply_transform(T)
    return m

def pad(x, z0, z1):
    c = cylinder(radius=PAD_D / 2, height=z1 - z0, sections=64)
    c.apply_translation([x, 0, (z0 + z1) / 2])
    return c

def dovetail(z0, z1, grow):
    """Channel cross-section between heights z0 and z1, widened by `grow` per side."""
    def half(z):
        return CH_BOT / 2 - (z - FLOOR) / math.tan(math.radians(SLOPE)) + grow
    return [(-half(z0), z0), (half(z0), z0), (half(z1), z1), (-half(z1), z1)]

def build(clr=CLR):
    rail = B(0, L, -W / 2, W / 2, 0, RAIL_H)
    cuts = [prism(dovetail(FLOOR, RAIL_H + 0.01, 0), FRONT_WALL, L + 1),
            B(GATE_X0, GATE_X0 + GATE_T, -GATE_W / 2, GATE_W / 2, FLOOR, RAIL_H + 1),
            B(GATE_X0, GATE_X0 + GATE_T, -W, W, SLOT_Z, RAIL_H + 1)]
    if PAD_DEPTH > 0: cuts += [pad(x, -1, PAD_DEPTH) for x in PADS_X]
    rail = trimesh.boolean.difference([rail] + cuts)

    deck = B(0, L, -W / 2, W / 2, RAIL_H, RAIL_H + DECK)
    key = prism(dovetail(FLOOR + KEY_LIFT, RAIL_H + 0.01, -clr), KEY_X0, KEY_X1)
    runner = trimesh.boolean.union([deck, key])
    if PAD_DEPTH > 0: runner = trimesh.boolean.difference([runner] + [pad(x, RAIL_H + DECK - PAD_DEPTH, RAIL_H + DECK + 1) for x in PADS_X])

    def stop(centres):
        y0, y1 = min(centres) - W / 2 + 0.2, max(centres) + W / 2 - 0.2
        parts = [B(GATE_X0 + GATE_CLR, GATE_X0 + GATE_T - GATE_CLR, y0, y1, SLOT_Z + 0.2, RAIL_H - 0.2)]
        parts += [B(GATE_X0 + GATE_CLR, GATE_X0 + GATE_T - GATE_CLR, c - GATE_W / 2 + GATE_CLR, c + GATE_W / 2 - GATE_CLR,
                    FLOOR, SLOT_Z + 0.3) for c in centres]
        return trimesh.boolean.union(parts)
    gate = stop([0.0])
    global TIE
    TIE = stop([-SPACING / 2, SPACING / 2])
    return rail, runner, gate

TIE = None

def moved_y(m, dy):
    c = m.copy(); c.apply_translation([0, dy, 0]); return c

def ivol(a, b):
    m = trimesh.boolean.intersection([a, b])
    return 0.0 if m.is_empty else float(abs(m.volume))

def moved(m, dx):
    c = m.copy(); c.apply_translation([dx, 0, 0]); return c

def main():
    rail, runner, gate = build()
    out, ok = [], True
    def chk(name, cond, detail=""):
        nonlocal ok
        ok &= bool(cond); out.append(dict(check=name, ok=bool(cond), detail=detail))
    for nm, m in (("rail", rail), ("runner", runner), ("gate", gate), ("tie", TIE)):
        chk(f"{nm}: watertight", m.is_watertight)
        n = len(m.split(only_watertight=False)); chk(f"{nm}: one body", n == 1, f"bodies={n}")
        chk(f"{nm}: fits bed", max(m.extents) <= 250, f"extents={np.round(m.extents, 2).tolist()}")
    # the joint, at home and at every 10 mm of travel
    worst = max(ivol(rail, moved(runner, -d)) for d in range(0, int(TRAVEL) + 1, 10))
    chk("runner clears rail over the whole travel", worst < 1e-6, f"max interference mm3={worst:.6f}")
    chk("runner clears gate at home", ivol(gate, runner) < 1e-6)
    # negative control: the same measurement must see a key built with no clearance and no lift
    _, tight, _ = build(clr=-0.2)
    v = ivol(rail, tight)
    chk("NEGATIVE CONTROL: oversize key is detected", v > 1.0, f"interference mm3={v:.2f}")
    # the stops are real: one millimetre past each end collides
    v = ivol(rail, moved(runner, -(TRAVEL + 1.0)))
    chk("forward stop: travel+1 mm collides with the front wall", v > 1.0, f"mm3={v:.2f}")
    v = ivol(gate, moved(runner, +1.0))
    chk("rear stop: 1 mm behind home collides with the gate", v > 1.0, f"mm3={v:.2f}")
    # the key cannot lift out: raise the runner 1 mm, it must hit the dovetail walls
    up = runner.copy(); up.apply_translation([0, 0, 1.0])
    v = ivol(rail, up)
    chk("key is captive: a 1 mm lift collides", v > 1.0, f"mm3={v:.2f}")
    # the tie bar: sits in both rails without touching, and locates them sideways both ways
    pair = [moved_y(rail, -SPACING / 2), moved_y(rail, SPACING / 2)]
    chk("gate clears its rail", ivol(gate, rail) < 1e-6)
    chk("tie bar clears both rails", max(ivol(TIE, p) for p in pair) < 1e-6)
    for dy in (-1.0, 1.0):
        v = ivol(TIE, moved_y(pair[0], dy))
        chk(f"tie bar locates a rail: moved {dy:+.0f} mm sideways it collides", v > 1.0, f"mm3={v:.2f}")
    v = ivol(TIE, moved_y(moved(runner, +1.0), SPACING / 2))
    chk("rear stop with the tie bar: 1 mm behind home collides", v > 1.0, f"mm3={v:.2f}")
    chk("rails fit under the tank", SPACING + W <= TANK["w"], f"outer width {SPACING + W:.0f} of {TANK['w']:.0f}")
    # the gate is covered by the deck at home (cannot lift), uncovered at full travel
    chk("deck covers the gate at home", L >= GATE_X0 + GATE_T)
    # statics
    cg_home = TANK["d"] / 2                              # tank front flush with the runner front
    cg_out = cg_home - TRAVEL
    chk("tank centre stays over the rail at full travel", 0 < cg_out < L, f"cg at x={cg_out:.0f} of 0..{L:.0f}")
    chk("tank centre stays between the pads", PADS_X[0] < cg_home < PADS_X[1], f"cg {cg_home:.0f}, pads {PADS_X}")
    F = TANK["kg_full"] * 9.81 / 2
    sig = 6 * F * TRAVEL / (W * DECK ** 2)               # whole rail load on the tip of the overhang
    chk("deck overhang, worst case, under 20 MPa", sig < 20, f"sigma={sig:.1f} MPa at {F:.0f} N per rail")
    # export: rail as modelled; runner flipped (deck on the bed); gate flat
    rail.export("slide_rail.stl")
    r = runner.copy(); r.apply_transform(trimesh.transformations.rotation_matrix(math.pi, [1, 0, 0]))
    r.apply_translation(-r.bounds[0]); r.export("slide_runner.stl")
    g = gate.copy(); g.apply_transform(trimesh.transformations.rotation_matrix(math.pi / 2, [0, 1, 0]))
    g.apply_translation(-g.bounds[0]); g.export("slide_gate.stl")
    t = TIE.copy(); t.apply_transform(trimesh.transformations.rotation_matrix(math.pi / 2, [0, 1, 0]))
    t.apply_translation(-t.bounds[0]); t.export("slide_tie.stl")
    runner.export("slide_runner_modelframe.stl"); gate.export("slide_gate_modelframe.stl")
    for f in ("slide_rail.stl", "slide_runner.stl", "slide_gate.stl", "slide_tie.stl"):
        m = trimesh.load(f)
        chk(f"{f}: reloads as one watertight body", m.is_watertight and len(m.split(only_watertight=False)) == 1,
            f"vol cm3={m.volume / 1000:.1f} extents={np.round(m.extents, 2).tolist()}")
    dims = dict(channel_top=round(CH_TOP, 2), key_top=round(CH_TOP - 2 * CLR, 2), stack_height=RAIL_H + DECK,
                key_len=KEY_X1 - KEY_X0, travel=TRAVEL)
    json.dump(dict(ok=ok, dims=dims, checks=out), open("checks.json", "w"), indent=1)
    for c in out: print("PASS" if c["ok"] else "FAIL", c["check"], c["detail"])
    print(dims); print("ALL OK" if ok else "FAILED"); sys.exit(0 if ok else 1)

main()
