"""Bob Bot exterior shell set + printed leg link. Own style (faceted, split halves, insert bosses).
Derived design, not built. CERN-OHL-S-2.0. Units mm; link frames = Asimov 1 MJCF body frames."""
import cadquery as cq, json, os, sys, math
OUT = sys.argv[1] if len(sys.argv) > 1 else "out"
WALL, GAP, INS = 2.2, 5.0, 2.0   # wall, clearance to link bbox, M3 heat-set hole radius (4.0 mm)
# link bboxes (m) from the MJCF STL meshes: (min xyz, max xyz)
BB = {
 "thigh":     ("left_hip_yaw_link",   (-0.056,-0.055,-0.232), (0.068,0.060,0.020), "z"),
 "shin":      ("left_knee_link",      (-0.067,-0.049,-0.290), (0.061,0.052,0.000), "z"),
 "upper_arm": ("left_shoulder_yaw_link", (-0.040,-0.037,-0.139), (0.040,0.038,0.005), "z"),
 "forearm":   ("left_elbow_link",     (0.000,-0.039,-0.039), (0.108,0.041,0.039), "x"),
 "pelvis":    ("pelvis_link",         (-0.124,-0.070,-0.104), (0.008,0.069,0.080), "z"),
}
def oct_prism(w, d, L, c):
    """chamfered-rectangle (octagon) section w x d, length L along +Z from 0."""
    pts = [(-w/2+c,-d/2),(w/2-c,-d/2),(w/2,-d/2+c),(w/2,d/2-c),(w/2-c,d/2),(-w/2+c,d/2),(-w/2,d/2-c),(-w/2,-d/2+c)]
    return cq.Workplane("XY").polyline(pts).close().extrude(L)
def sleeve(w, d, L, name):
    c = 0.28*min(w, d)
    outer = oct_prism(w, d, L, c)
    inner = oct_prism(w-2*WALL, d-2*WALL, L+2, max(c-WALL*0.6, 1)).translate((0,0,-1))
    s = outer.cut(inner)
    # accent groove band (1 mm deep) at 72 % height
    band = oct_prism(w+2, d+2, 6, c+1).cut(oct_prism(w-2, d-2, 6, c)).translate((0,0,0.72*L))
    s = s.cut(band)
    # end chamfer ring (taper) at bottom
    halves = {}
    for side, sgn in (("front", 1), ("back", -1)):
        box = cq.Workplane("XY").box(w+20, d+20, L+20, centered=(True, True, False)).translate((sgn*(w+20)/2, 0, -10))
        h = s.intersect(box)
        for z in (0.15*L, 0.85*L):        # boss tabs on the split plane, inside the shell
            for y in (-(d/2-WALL-4), d/2-WALL-4):
                boss = cq.Workplane("YZ").center(y, z).circle(4.5).extrude(sgn*7)
                hole = cq.Workplane("YZ").center(y, z).circle(INS if side=="front" else 1.7).extrude(sgn*7)
                h = h.union(boss).cut(hole)
        halves[side] = h
    return halves
parts = {}; place = {}
for name, (body, lo, hi, ax) in BB.items():
    lo = [x*1000 for x in lo]; hi = [x*1000 for x in hi]
    if ax == "z":
        w, d, L = hi[0]-lo[0]+2*GAP, hi[1]-lo[1]+2*GAP, hi[2]-lo[2]
        hv = sleeve(w, d, L, name); pos = ((lo[0]+hi[0])/2, (lo[1]+hi[1])/2, lo[2]); quat = (1,0,0,0)
    else:  # along +x: build along z then rotate z->x
        w, d, L = hi[2]-lo[2]+2*GAP, hi[1]-lo[1]+2*GAP, hi[0]-lo[0]
        hv = sleeve(w, d, L, name); pos = (lo[0], (lo[1]+hi[1])/2, (lo[2]+hi[2])/2); quat = (0.70710678, 0, 0.70710678, 0)
    for side, h in hv.items():
        parts[f"{name}_{side}"] = h; place[f"{name}_{side}"] = dict(body=body, pos=[p/1000 for p in pos], quat=quat, mirror_right=True)
# torso: chest + back shell with access panel; head with visor
def torso():
    lo, hi = (-117, -125, -3), (102, 125, 378)
    w, d, L = hi[0]-lo[0]+2*GAP, hi[1]-lo[1]+2*GAP, 300
    c = 0.22*min(w, d)
    shell = oct_prism(w, d, L, c).cut(oct_prism(w-2*WALL, d-2*WALL, L+2, c-1).translate((0,0,-1)))
    shell = shell.cut(oct_prism(w+2, d+2, 6, c+1).cut(oct_prism(w-2, d-2, 6, c)).translate((0,0,0.8*L)))
    chest = shell.intersect(cq.Workplane("XY").box(w, d+20, L+20, centered=(False, True, False)).translate((0, 0, -10)))
    back = shell.intersect(cq.Workplane("XY").box(w, d+20, L+20, centered=(False, True, False)).translate((-w, 0, -10)))
    win = cq.Workplane("YZ").center(0, L*0.45).rect(0.55*d, 0.45*L).extrude(-w)
    back = back.cut(win)
    panel = cq.Workplane("YZ").center(0, L*0.45).rect(0.55*d + 10, 0.45*L + 10).extrude(-WALL).translate((-w/2 - 0.2, 0, 0))
    for yy in (-(0.55*d/2), 0.55*d/2):
        for zz in (L*0.45-0.45*L/2-2.5, L*0.45+0.45*L/2+2.5):
            panel = panel.cut(cq.Workplane("YZ").center(yy, zz).circle(1.7).extrude(-10).translate((-w/2+2, 0, 0)))
    for p in (chest, back):
        pass
    pos = [((lo[0]+hi[0])/2)/1000, 0, 0.040]
    return {"chest": chest, "back": back, "access_panel": panel}, pos
def head():
    w, d, L = 175, 140, 150
    c = 30
    s = oct_prism(w, d, L, c).cut(oct_prism(w-2*WALL, d-2*WALL, L-WALL, c-1))
    s = s.edges(">Z").chamfer(12)
    visor_cut = cq.Workplane("YZ").center(0, 0.62*L).rect(0.75*d, 0.22*L).extrude(-30).translate((w/2+5, 0, 0))
    shell = s.cut(visor_cut)
    visor = cq.Workplane("YZ").center(0, 0.62*L).rect(0.75*d+8, 0.22*L+8).extrude(-1.5).translate((w/2 - WALL + 1.5, 0, 0))
    return {"head_shell": shell, "visor": visor}, [0.012, 0, -0.03]
tp, tpos = torso(); hp, hpos = head()
for k, v in tp.items(): parts[k] = v; place[k] = dict(body="waist_yaw_link", pos=tpos, quat=(1,0,0,0), mirror_right=False)
for k, v in hp.items(): parts[k] = v; place[k] = dict(body="neck_pitch_link", pos=hpos, quat=(1,0,0,0), mirror_right=False)

# printed leg link: 2 clamp blocks + 2 bought 25 mm tubes (thigh), DIY-L output flange pattern
def leg_link(L=150.0, pitch=44.0):
    blk = cq.Workplane("XY").box(90, 40, 34)
    for x in (-pitch/2, pitch/2):
        blk = blk.cut(cq.Workplane("XY").center(x, 0).circle(12.6).extrude(40).translate((0, 0, -20)))
        blk = blk.cut(cq.Workplane("XZ").center(x, 0).rect(1.5, 40).extrude(-30).translate((0, 0, 0)) if False else cq.Workplane("XY").box(1.5, 25, 40).translate((x, 12.5+8, 0)))
        blk = blk.cut(cq.Workplane("XZ").center(x+16.5 if x > 0 else x-16.5, 8).circle(1.7).extrude(-40).translate((0, 20, 0)))
    flange = cq.Workplane("XZ").circle(37).extrude(8).translate((0, -20, 0))
    for k in range(6):
        a = 2*math.pi*k/6 + math.pi/6
        flange = flange.cut(cq.Workplane("XZ").center(29*math.cos(a), 29*math.sin(a)).circle(1.7).extrude(8).translate((0, -20, 0)))
    clamp = blk.union(flange.translate((0, 0, 0)))
    tube = cq.Workplane("XY").circle(12.5).circle(10).extrude(L)
    return clamp, tube
clamp, tube = leg_link()
parts["leg_clamp"] = clamp; parts["leg_tube_25x20x150"] = tube
os.makedirs(f"{OUT}/shells", exist_ok=True)
vol = {}
for k, v in parts.items():
    cq.exporters.export(v, f"{OUT}/shells/{k}.step"); cq.exporters.export(v, f"{OUT}/shells/{k}.stl", tolerance=0.1, angularTolerance=0.2)
    vol[k] = round(v.val().Volume()/1000, 1)
json.dump(dict(place=place, vol_cm3=vol), open(f"{OUT}/shells/shells.json", "w"), indent=1)
print(vol)
