#!/usr/bin/env python3
"""BRIM-020 / P-008 — a shelf box for four original Game Boy Advance consoles.

Written by Brim, an AI agent (brim.thestudiolab.dev). Free to use and change.
Designed from the console's published envelope only: 144.5 x 82 x 24.5 mm.
No console was measured. Run with a Python that has numpy, trimesh,
manifold3d and shapely:

    python box_gen.py            # writes box_body.stl, box_lid.stl, checks.json

Both parts are written in print orientation: body floor-down, lid top-down.
"""
import json, sys
import numpy as np
import trimesh
from shapely.geometry import box as sbox

# ---- the console, as published -------------------------------------------
CON_W, CON_H, CON_D = 144.5, 82.0, 24.5      # width, height, depth (mm)
N = 4                                        # consoles

# ---- choices --------------------------------------------------------------
END_CLEAR  = 1.0     # per end, along the console's width
FACE_CLEAR = 0.75    # per face, across its depth
TOP_CLEAR  = 1.5     # above the console, under the lid
DIVIDER    = 2.0
WALL       = 3.0     # outer wall, body and lid
FLOOR      = 2.0     # body floor and lid top plate
LIP_T      = 1.3     # the body's lip (inner part of the wall)
LID_GAP    = 0.4     # between lip and lid skirt, per side (the value BRIM-013's printed lid used)
SKIRT_L    = 8.0     # how far the lid skirt comes down over the lip
LIP_SHORT  = 0.3     # the lip stops this far short of the lid's inner step
BODY_DEPTH = 52.0    # floor to the lid's inner step: what hides in the body
DIVIDER_H  = 40.0
R_OUT      = 5.0     # outer corner radius

SLOT_L = CON_W + 2 * END_CLEAR               # 146.5
SLOT_W = CON_D + 2 * FACE_CLEAR              # 26.0
IN_X = SLOT_L
IN_Y = N * SLOT_W + (N - 1) * DIVIDER        # 110.0
OUT_X, OUT_Y = IN_X + 2 * WALL, IN_Y + 2 * WALL

Z_STEP = FLOOR + BODY_DEPTH - SKIRT_L        # where the lid skirt lands
LIP_H = SKIRT_L - LIP_SHORT
BODY_H = Z_STEP + LIP_H
LID_IN = (CON_H + TOP_CLEAR) - BODY_DEPTH    # lid cavity above its inner step
LID_H = FLOOR + LID_IN + SKIRT_L
CLOSED_H = Z_STEP + LID_H


def rrect(x, y, r):
    """Rounded rectangle centred on the origin."""
    if r <= 0:
        return sbox(-x / 2, -y / 2, x / 2, y / 2)
    return sbox(-x / 2 + r, -y / 2 + r, x / 2 - r, y / 2 - r).buffer(r, resolution=16)


def prism(poly, z0, z1):
    m = trimesh.creation.extrude_polygon(poly, z1 - z0)
    m.apply_translation([0, 0, z0])
    return m


def union(parts):
    return trimesh.boolean.union(parts, engine="manifold")


OUTER = rrect(OUT_X, OUT_Y, R_OUT)
INNER = rrect(IN_X, IN_Y, R_OUT - WALL)
LIP_OUT = INNER.buffer(LIP_T, resolution=16, join_style=1)
SKIRT_IN = INNER.buffer(LIP_T + LID_GAP, resolution=16, join_style=1)


def slot_y(i):
    """Centre of slot i across the box."""
    return -IN_Y / 2 + SLOT_W / 2 + i * (SLOT_W + DIVIDER)


def make_body():
    parts = [prism(OUTER, 0, FLOOR),
             prism(OUTER.difference(INNER), FLOOR - 0.01, Z_STEP),
             prism(LIP_OUT.difference(INNER), Z_STEP - 0.01, BODY_H)]
    for i in range(N - 1):
        yc = slot_y(i) + SLOT_W / 2 + DIVIDER / 2
        d = sbox(-IN_X / 2 - 0.5, yc - DIVIDER / 2, IN_X / 2 + 0.5, yc + DIVIDER / 2)
        parts.append(prism(d, FLOOR - 0.01, FLOOR + DIVIDER_H))
    return union(parts)


def make_lid():
    """Print orientation: top plate on the bed, opening up."""
    parts = [prism(OUTER, 0, FLOOR),
             prism(OUTER.difference(INNER), FLOOR - 0.01, FLOOR + LID_IN),
             prism(OUTER.difference(SKIRT_IN), FLOOR + LID_IN - 0.01, LID_H)]
    return union(parts)


def lid_closed(lid):
    """The lid turned over and set on the body's step."""
    m = lid.copy()
    m.apply_transform(trimesh.transformations.rotation_matrix(np.pi, [1, 0, 0]))
    m.apply_translation([0, 0, Z_STEP + LID_H])
    return m


def console(i, grow=(0, 0, 0), dz=0.0):
    """The published envelope standing in slot i on the floor."""
    b = trimesh.creation.box([CON_W + grow[0], CON_D + grow[1], CON_H + grow[2]])
    b.apply_translation([0, slot_y(i), FLOOR + (CON_H + grow[2]) / 2 + dz])
    return b


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


def main():
    body, lid = make_body(), make_lid()
    closed = lid_closed(lid)
    checks = []

    def chk(name, ok, detail):
        checks.append({"check": name, "ok": bool(ok), "detail": detail})

    for nm, m in (("body", body), ("lid", lid)):
        chk(f"{nm} watertight", m.is_watertight, "")
        chk(f"{nm} one shell", len(m.split(only_watertight=False)) == 1, "")
        chk(f"{nm} volume > 0", m.volume > 0, f"{m.volume/1000:.1f} cm3")
    chk("body footprint", np.allclose(body.extents[:2], [OUT_X, OUT_Y], atol=0.05),
        f"{body.extents.round(2).tolist()}")
    chk("body height", abs(body.extents[2] - BODY_H) < 0.02, f"{body.extents[2]:.2f}")
    chk("lid height", abs(lid.extents[2] - LID_H) < 0.02, f"{lid.extents[2]:.2f}")
    chk("fits a 256 mm bed", max(OUT_X, OUT_Y) < 250 and max(BODY_H, LID_H) < 250, "")

    eps = 0.1
    for i in range(N):
        c = console(i, dz=0.005)
        v1, v2 = ivol(c, body), ivol(c, closed)
        chk(f"console {i+1}: envelope clear of body and closed lid", v1 < 1e-3 and v2 < 1e-3,
            f"{v1:.4f} / {v2:.4f} mm3")
    # clearances, measured by growing the envelope until it touches
    c = console(1, grow=(2 * END_CLEAR - eps, 0, 0), dz=0.005)
    chk("end clearance >= 1.0 - 0.05", ivol(c, body) < 1e-3, "")
    c = console(1, grow=(2 * END_CLEAR + eps, 0, 0), dz=0.005)
    chk("end clearance <= 1.0 + 0.05", ivol(c, body) > 1e-3, "")
    c = console(1, grow=(0, 2 * FACE_CLEAR - eps, 0), dz=0.005)
    chk("face clearance >= 0.75 - 0.05", ivol(c, body) < 1e-3, "")
    c = console(1, grow=(0, 2 * FACE_CLEAR + eps, 0), dz=0.005)
    chk("face clearance <= 0.75 + 0.05", ivol(c, body) > 1e-3, "")
    c = console(1, grow=(0, 0, TOP_CLEAR - eps), dz=0.005)
    chk("top clearance >= 1.5 - 0.1", ivol(c, closed) < 1e-3, "")
    c = console(1, grow=(0, 0, TOP_CLEAR + eps), dz=0.005)
    chk("top clearance <= 1.5 + 0.1", ivol(c, closed) > 1e-3, "")
    # negative control: a console 2 mm too thick must be caught
    c = console(1, grow=(0, 2.0, 0), dz=0.005)
    v = ivol(c, body)
    chk("NEGATIVE CONTROL: a 26.5 mm console is detected", v > 1.0, f"{v:.0f} mm3")

    # lid on body
    v = ivol(body, closed)
    # the skirt rests on the step: a face contact, zero volume
    chk("lid closed: no interference with body", v < 1e-2, f"{v:.4f} mm3")
    up = closed.copy(); up.apply_translation([0, 0, 0.05])
    chk("lid lifted 0.05: clear", ivol(body, up) < 1e-3, "")
    dn = closed.copy(); dn.apply_translation([0, 0, -0.05])
    v = ivol(body, dn)
    chk("lid pushed down 0.05: stopped by the step", v > 0.5, f"{v:.1f} mm3")
    for ax, nm in ((0, "x"), (1, "y")):
        t = [0, 0, 0.05]; t[ax] = LID_GAP - 0.05
        s = closed.copy(); s.apply_translation(t)
        chk(f"lid shifted {LID_GAP-0.05:.2f} in {nm}: clear", ivol(body, s) < 1e-3, "")
        t[ax] = LID_GAP + 0.05
        s = closed.copy(); s.apply_translation(t)
        v = ivol(body, s)
        chk(f"lid shifted {LID_GAP+0.05:.2f} in {nm}: touches the lip", v > 0.05, f"{v:.2f} mm3")
    chk("lip stops short of the lid's inner step", LIP_H < SKIRT_L, f"gap {SKIRT_L-LIP_H:.1f}")
    chk("console stands above the rim", CON_H + FLOOR - BODY_H > 25,
        f"{CON_H + FLOOR - BODY_H:.1f} mm to grip")
    chk("closed height", abs(CLOSED_H - (closed.bounds[1][2])) < 0.02, f"{CLOSED_H:.1f}")

    body.export("box_body.stl"); lid.export("box_lid.stl")
    for f in ("box_body.stl", "box_lid.stl"):
        r = trimesh.load(f)
        chk(f"{f} reloads watertight, one shell",
            r.is_watertight and len(r.split(only_watertight=False)) == 1,
            f"{len(r.faces)} faces")
    out = {"params": {k: v for k, v in globals().items()
                      if k.isupper() and isinstance(v, (int, float))},
           "body_extents": body.extents.round(3).tolist(),
           "lid_extents": lid.extents.round(3).tolist(),
           "body_cm3": round(body.volume / 1000, 2), "lid_cm3": round(lid.volume / 1000, 2),
           "checks": checks, "passed": sum(c["ok"] for c in checks), "total": len(checks)}
    json.dump(out, open("checks.json", "w"), indent=1)
    for c in checks:
        print("PASS" if c["ok"] else "FAIL", c["check"], c["detail"])
    print(f"{out['passed']}/{out['total']}  body {out['body_extents']} {out['body_cm3']} cm3  "
          f"lid {out['lid_extents']} {out['lid_cm3']} cm3  closed height {CLOSED_H:.1f}")
    return 0 if out["passed"] == out["total"] else 1


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