"""Demo-device puck enclosure (two printable shells). Units mm, Z up, origin = centre of the bottom face."""
import math, json, os
import numpy as np
import manifold3d as mf
import trimesh

SEG = 128
def cyl(r, z0, z1, r_top=None, seg=SEG):
    return mf.Manifold.cylinder(z1 - z0, r, r if r_top is None else r_top, seg).translate([0, 0, z0])
def at(m, x, y): return m.translate([x, y, 0])
def polar(r, deg): return r * math.cos(math.radians(deg)), r * math.sin(math.radians(deg))
def box(x0, y0, z0, x1, y1, z1): return mf.Manifold.cube([x1 - x0, y1 - y0, z1 - z0]).translate([x0, y0, z0])

# ---------------------------------------------------------------- key dimensions
R_OUT, R_IN = 39.0, 37.0           # 78 mm puck, 2 mm walls
H_SPLIT, H_TOP = 12.0, 30.0        # bottom shell 0..12, top shell 12..30
FLOOR = 2.0
PCB_Z0, PCB_T, PCB_R = 13.5, 1.6, 33.0
SCREW_R, SCREW_ANG = 30.0, (0, 120, 240)
MAG_RI, MAG_RO, MAG_T = 21.5, 26.5, 2.0   # MagSafe-style ring of 18 N52 arc magnets, 53 mm OD
RING_ZB, RING_ZT, RING_RI = 9.5, 12.0, 36.9  # 360-degree light ring at the seam
LED_ANGS = (60, 180, 300)                    # three side-view RGB LEDs under the board edge
USB_ANG, LED_ANG, BTN_ANG = 180, 206, 152
USB_Z = PCB_Z0 + PCB_T + 1.0 + 1.6  # XIAO board top + half the USB-C height

# ---------------------------------------------------------------- bottom shell: sensor side, vented floor
bot = cyl(R_OUT - 1.5, 0, 1.5, R_OUT) + cyl(R_OUT, 1.5, H_SPLIT)
bot = bot - cyl(R_IN, FLOOR, H_SPLIT + 1)
vents = []
pitch = 4.2
for j in range(-8, 9):
    for i in range(-8, 9):
        x = i * pitch + (pitch / 2 if j % 2 else 0); y = j * pitch * 0.866
        if math.hypot(x, y) < 25.5:
            vents.append(at(cyl(1.1, -1, FLOOR + 1, seg=20), x, y))
bot = bot - mf.Manifold.batch_boolean(vents, mf.OpType.Add)
for a in SCREW_ANG:                # standoffs carry the PCB, screws come up from below
    x, y = polar(SCREW_R, a)
    bot = bot + at(cyl(2.75, FLOOR - 0.1, PCB_Z0, seg=40), x, y)
    bot = bot - at(cyl(1.2, -1, PCB_Z0 + 1, seg=24), x, y) - at(cyl(2.2, -1, 1.6, seg=32), x, y)
# the bottom shell's wall stops at RING_ZB: the light ring sits on it, flush with the outside
bot = bot - (cyl(R_OUT + 1, RING_ZB, H_SPLIT + 1) - cyl(RING_RI - 0.05, RING_ZB - 1, H_SPLIT + 2))
# shallow pocket that locates the hydrophobic membrane disc (52 mm) over the vents
bot = bot - cyl(26.2, FLOOR - 0.3, FLOOR + 0.01)

# ---------------------------------------------------------------- top shell: electronics + battery, magnets in the roof
top = cyl(R_OUT, H_SPLIT, H_TOP - 2.0) + cyl(R_OUT, H_TOP - 2.0, H_TOP, R_OUT - 2.0)
top = top - cyl(R_IN, H_SPLIT - 1, H_TOP - FLOOR)
top = top + (cyl(36.8, H_SPLIT - 3.0, H_SPLIT + 0.01) - cyl(35.7, H_SPLIT - 4, H_SPLIT + 1))   # tongue into the bottom shell
for a in SCREW_ANG:
    x, y = polar(SCREW_R, a)
    top = top + at(cyl(2.75, PCB_Z0 + PCB_T, H_TOP - FLOOR + 0.1, seg=40), x, y)
    top = top - at(cyl(0.85, PCB_Z0, H_TOP - FLOOR - 1.0, seg=20), x, y)      # M2 self-tap pilot
# magnet ring: a boss under the roof with an annular pocket, 0.6 mm skin to the outside, magnets glued in from inside
top = top + (cyl(MAG_RO + 0.7, H_TOP - FLOOR - 2.2, H_TOP - FLOOR + 0.1) - cyl(MAG_RI - 0.7, H_TOP - FLOOR - 3, H_TOP))
top = top - (cyl(MAG_RO, H_TOP - FLOOR - 2.3, H_TOP - 0.6) - cyl(MAG_RI, H_TOP - FLOOR - 3, H_TOP))
# side openings: USB-C (charging + programming), LED light pipe, button
def side_hole(ang, w, h, z, depth=6.0):
    m = box(-depth / 2, -w / 2, z - h / 2, depth / 2, w / 2, z + h / 2)
    return m.rotate([0, 0, ang]).translate([*polar(R_OUT - 1.0, ang), 0])
top = top - side_hole(USB_ANG, 9.6, 4.0, USB_Z)
# windows in the tongue so each LED shines into the light ring
for a in LED_ANGS:
    top = top - box(-3, -5, RING_ZB - 0.5, 3, 5, H_SPLIT + 0.5).translate([0, 0, 0]).rotate([0, 0, a]).translate([*polar(36.2, a), 0])
bt = cyl(1.9, -4, 4, seg=24).rotate([0, 90, 0]).rotate([0, 0, BTN_ANG]).translate([*polar(R_OUT - 1.0, BTN_ANG), PCB_Z0 + PCB_T + 1.8])
top = top - bt
# a shallow ring groove on the roof marks the magnet ring
top = top - (cyl(MAG_RO + 0.5, H_TOP - 0.4, H_TOP + 1) - cyl(MAG_RO - 0.5, H_TOP - 1, H_TOP + 2))

# light ring (clear PETG or acrylic, frosted) and the adhesive steel mounting ring
light_ring = cyl(R_OUT, RING_ZB, RING_ZT) - cyl(RING_RI, RING_ZB - 1, RING_ZT + 1)
steel_ring = cyl(28.0, 0, 0.5) - cyl(21.0, -1, 1)

def save(m, path):
    mesh = m.to_mesh()
    tm = trimesh.Trimesh(vertices=mesh.vert_properties[:, :3], faces=mesh.tri_verts, process=True)
    tm.export(path)
    return tm
out = os.path.dirname(os.path.abspath(__file__)) + os.sep
tb = save(bot, out + "puck_bottom_shell.stl")
tt = save(top, out + "puck_top_shell.stl")
save(light_ring, out + "puck_light_ring.stl")
save(steel_ring, out + "steel_mount_ring.stl")
info = dict(
    R_OUT=R_OUT, R_IN=R_IN, H_SPLIT=H_SPLIT, H_TOP=H_TOP, FLOOR=FLOOR, PCB_Z0=PCB_Z0, PCB_T=PCB_T, PCB_R=PCB_R,
    SCREW_R=SCREW_R, SCREW_ANG=SCREW_ANG, MAG_RI=MAG_RI, MAG_RO=MAG_RO, MAG_T=MAG_T, RING_ZB=RING_ZB, RING_ZT=RING_ZT, RING_RI=RING_RI, LED_ANGS=LED_ANGS, USB_ANG=USB_ANG, BTN_ANG=BTN_ANG, USB_Z=USB_Z,
    vents=len(vents),
    bottom=dict(watertight=tb.is_watertight, volume_cm3=round(tb.volume / 1000, 2), bounds=tb.bounds.round(2).tolist()),
    top=dict(watertight=tt.is_watertight, volume_cm3=round(tt.volume / 1000, 2), bounds=tt.bounds.round(2).tolist()))
json.dump(info, open(out + "puck.json", "w"), indent=1)
print(json.dumps(info, indent=1))
