"""AuraPulse v4.4 : jeu reduit sur les grands cotes de la vitre (0,22 mm).
AuraPulse case for the Waveshare ESP32-C6-Touch-LCD-2.8 -- v4.3, 16 November 2026.
v4.3 = v4.2 (gold front rim, cut by split_rim.py) with a rim 0.8 mm above the glass (was 0.2) and
  0.35 mm of play around the glass (was 0.2), after the first assembly: the glass now sits fully down
  and the rim stands clearly above it. The button stem is 0.15 mm longer accordingly.
v4 = the v2 case (fine flutes, four screws) with
  - M2.5 x 8 countersunk machine screws (90 deg head) going into the board's own standoffs,
  - a separate power button held by a shoulder, put in from the inside before the board,
    with two small clip lips that keep it in place during assembly. The shoulder idea
    comes from pixelwave's ESP32-S3 3.5 case (reused with permission, credited).
Every dimension below comes from one of three places, and nowhere else :
  [BOARD] measured on Waveshare's official STEP model of the board
  [PRINT] chosen for a 0.4 mm nozzle and 0.16 mm layers, printed back down, without slicer supports
  [USER]  decided for this project (battery, screws, rim above the glass)
"""
import cadquery as cq, numpy as np
V=cq.Vector
LAYER,LINE=0.16,0.4                                                    # [PRINT]
# ---------------- [BOARD] ----------------
GLX,GLY,GT,GR = 50.54,73.06,0.70,2.0       # cover glass : size, thickness, corner radius
STAND = 10.20                              # front of the glass -> tip of the M2.5 standoffs
OFFY  = 3.0                                # glass centre sits at y = -3.0 in the STEP frame
ST = [(-20.435,27.11),(20.565,27.10),(-20.44,-32.89),(20.56,-32.90)]   # standoffs
KEY_Y, KEY_Zb, KEY_X = 3.62, -6.40, 24.89                              # PWR push button (KEY1)
BODY_Y0,BODY_Y1 = -38.28,31.70                                         # what sits behind the glass
USB_SHELL_W,USB_SHELL_H,USB_SHELL_ZC = 8.94,3.16,-7.17                 # USB-C receptacle shell, centred on x = 0
# ---------------- [PRINT] ----------------
WALL  = 6*LINE                             # 2.4 : six lines, so the flutes leave more than four
FLOOR = 8*LAYER                            # 1.28
CLG   = 0.35                               # play around the glass, top and bottom (v4.3 : 0.35, was 0.2)
CLG_X = 0.22                               # v4.4 : play on the long sides, where the gap showed (0.35 in v4.3)
CHAM  = 1.0                                # 45 deg chamfer on the plate
RTOP  = 1.2                                # rounding of the rim
FL_PITCH,FL_W,FL_D,FL_N = 1.5,1.1,0.55,16  # fine grip flutes : V section with 45 deg flanks
FL_Z0,FL_Z1 = 2.4,2.4                      # plain band left under and over the flutes
# ---------------- [USER] ----------------
BAT_CLEAR = 9.72                           # free height under the board for an 803040 cell and its adhesive
BAT_W,BAT_L = 30.6,40.6
RIB_H = FLOOR+3.2                          # low kerbs that keep the cell in place
SUBRIM = 0.8                               # v4.3 : rim stands 0.8 above the glass (0.2 in v4.2)
M_D,BOSS_D = 2.9,8.6                       # M2.5 clearance hole, boss
CSK_D,CSK_BORE = 5.4,5.8                   # v4 : countersunk head (5.0 nominal + play), access bore
SCREW_L,ENGAGE = 8.0,4.5                   # v4 : total length of a countersunk screw, thread in the standoff
USB_PLUG_W,USB_PLUG_H,USB_PLUG_R = 13.0,7.2,2.0   # room for a cable overmould (USB-C allows up to 12.35 x 6.5)
USB_PLAY = 0.25
# v4 button : round cap with two keys (anti-rotation) and a conical shoulder seated in a
# countersunk pocket cut from the inside of the wall. The cone (45 deg) lets the button
# print face down without any overhang.
CAP_D,CAP_PLAY = 7.6,0.18                  # cap diameter, radial play in the hole
KEY_W,KEY_H = 1.4,0.9                      # keys above and below the cap
FLANGE_R,RIM_T = 4.7,0.5                   # shoulder : outer radius, straight rim before the 45 deg cone
POCKET_PLAY = 0.2                          # radial play of the rim, axial play of the cone at rest
BACK_GAP = 0.06                            # back of the shoulder stands this far outside the inner wall face
PROUD = 0.8                                # cap stands this much out of the wall
TRAVEL_GAP = 0.10                          # stem -> switch at rest
LIP_BUMP = 0.20                            # clip lips : bump presses this much into the pocket wall
USB_FINS=(); BTN_FINS=();   # v4.1 : no props any more
FIN_W=0.86; FIN_GAP=0.13; BTN_FIN_GAP=0.2   # (props, unused since v4.1)
# ---------------- derived ----------------
BOSS_H = round(FLOOR+BAT_CLEAR,2)          # 11.0
ZG = BOSS_H+STAND; ZL = ZG-GT; H = ZG+SUBRIM; ZOFF = ZG-0.7
hx,hy,r = GLX/2+CLG_X, GLY/2+CLG, GR+CLG_X
OX,OY = hx+WALL, hy+WALL
CY0,CY1 = BODY_Y0+OFFY-0.22, BODY_Y1+OFFY+0.30
BX,BY,BZ = hx, KEY_Y+OFFY, KEY_Zb+ZOFF
PROF=[(-0.6,0),(WALL-CHAM,0),(WALL,CHAM),(WALL,H-RTOP)]+[(WALL-RTOP+RTOP*np.cos(a),H-RTOP+RTOP*np.sin(a)) for a in np.linspace(0,np.pi/2,9)[1:]]+[(-0.6,H)]

def rrect(hx_,hy_,r_,z0,z1): return cq.Workplane('XY').workplane(offset=z0).rect(2*hx_,2*hy_).extrude(z1-z0).edges('|Z').fillet(r_)
def box(x0,x1,y0,y1,z0,z1): return cq.Workplane('XY').box(x1-x0,y1-y0,z1-z0,centered=False).translate((x0,y0,z0))
def poly_face(pts): return cq.Face.makeFromWires(cq.Wire.makePolygon([V(*p) for p in pts],close=True))
def frustum(x0,L,ra,rb):
    f=cq.Workplane(obj=cq.Solid.makeCone(ra,rb,L,V(x0,BY-BTN_E,BZ),V(1,0,0)))
    f=f.union(cq.Workplane(obj=cq.Solid.makeCone(ra,rb,L,V(x0,BY+BTN_E,BZ),V(1,0,0))))
    tr=poly_face([(x0,BY-BTN_E,BZ-ra),(x0+L,BY-BTN_E,BZ-rb),(x0+L,BY-BTN_E,BZ+rb),(x0,BY-BTN_E,BZ+ra)])
    return f.union(cq.Workplane(obj=cq.Solid.extrudeLinear(tr,V(0,2*BTN_E,0))))
FL_Y0 = -(hy-r)+2.5                        # first flute, on the lower half where the hand holds it
def flutes():
    out=None
    for sx in(-1,1):
        for i in range(FL_N):
            yc=FL_Y0+FL_W/2+i*FL_PITCH
            tri=poly_face([(sx*(OX+0.3),yc-FL_W/2-0.3,0),(sx*(OX-FL_D),yc,0),(sx*(OX+0.3),yc+FL_W/2+0.3,0)])
            p=cq.Workplane(obj=cq.Solid.extrudeLinear(tri,V(0,0,H)))
            # 45 deg run-out at both ends : nothing to bridge, and the flute dies cleanly into the plain bands
            keep=poly_face([(sx*(OX+0.3),0,FL_Z0-0.3),(sx*(OX-FL_D-0.2),0,FL_Z0+FL_D+0.2),(sx*(OX-FL_D-0.2),0,H-FL_Z1-FL_D-0.2),(sx*(OX+0.3),0,H-FL_Z1+0.3)])
            k=cq.Workplane(obj=cq.Solid.extrudeLinear(keep,V(0,FL_W+1.0,0))).translate((0,yc-FL_W/2-0.5,0))
            p=p.intersect(k); out=p if out is None else out.union(p)
    return out
def make_case(fins=True):
    solids=[rrect(hx,hy,r,0,H).val()]
    L=2*(hy-r); solids.append(cq.Solid.extrudeLinear(poly_face([( hx+w,-(hy-r),z) for w,z in PROF]),V(0,L,0)))
    solids.append(cq.Solid.extrudeLinear(poly_face([(-hx-w,-(hy-r),z) for w,z in PROF]),V(0,L,0)))
    L=2*(hx-r); solids.append(cq.Solid.extrudeLinear(poly_face([(-(hx-r), hy+w,z) for w,z in PROF]),V(L,0,0)))
    solids.append(cq.Solid.extrudeLinear(poly_face([(-(hx-r),-hy-w,z) for w,z in PROF]),V(L,0,0)))
    for sx in(-1,1):
        for sy in(-1,1):
            cx,cy=sx*(hx-r),sy*(hy-r)
            solids.append(cq.Solid.revolve(poly_face([(cx+r+w,cy,z) for w,z in PROF]),360,V(cx,cy,0),V(cx,cy,1)))
    body=cq.Workplane(obj=solids[0])
    for s in solids[1:]: body=body.union(cq.Workplane(obj=s))
    body=body.cut(rrect(hx,hy,r,ZL,H+1))                                              # seat of the glass
    body=body.cut(box(-hx,hx,CY0,CY1,FLOOR,ZL+0.01).intersect(rrect(hx,hy,r,0,H)))    # cavity
    for x,y in ST: body=body.union(cq.Workplane('XY').workplane(offset=0.5).center(x,y+OFFY).circle(BOSS_D/2).extrude(BOSS_H-0.5))
    for x,y in ST: body=body.union(box(*sorted([x,np.sign(x)*(hx+0.3)]),y+OFFY-3.0,y+OFFY+3.0,0.5,BOSS_H))
    y0,y1=min(s[1] for s in ST)+OFFY,max(s[1] for s in ST)+OFFY
    for sx in(-1,1): body=body.union(box(*sorted([sx*BAT_W/2,sx*(BAT_W/2+2.0)]),y0,y1,0.5,RIB_H))
    for sy in(-1,1): body=body.union(box(-8,8,*sorted([sy*BAT_L/2,sy*(BAT_L/2+1.5)]),0.5,RIB_H))
    # v4 : countersunk M2.5 x 8. Head top at zt, tip ENGAGE mm into the standoff.
    zt=BOSS_H+ENGAGE-SCREW_L; hc=(CSK_D-M_D)/2      # 90 deg : cone height = radius difference
    for x,y in ST:
        body=body.cut(cq.Workplane('XY').workplane(offset=-1).center(x,y+OFFY).circle(M_D/2).extrude(BOSS_H+2))
        body=body.cut(cq.Workplane('XY').workplane(offset=-1).center(x,y+OFFY).circle(CSK_BORE/2).extrude(zt+1))
        body=body.cut(cq.Workplane(obj=cq.Solid.makeCone(CSK_D/2,M_D/2,hc,V(x,y+OFFY,zt),V(0,0,1))))
    # USB-C : a window the size of the receptacle, then a straight pocket for the cable overmould, chamfered at the mouth
    zu=USB_SHELL_ZC+ZOFF; yi=CY0; LIP=0.8; usbcut=[]
    def prism(w,h,rad,ya,yb):
        # v4.1 : rounded at the bottom, 45 deg chamfers at the top -> the roof is a flat bridge
        # and the corners are self-supporting : the opening prints without any prop
        rad=min(rad,h/2-0.01,w/2-0.01); pts=[]
        for a in np.linspace(np.pi,1.5*np.pi,7): pts.append((-w/2+rad+rad*np.cos(a),zu-h/2+rad+rad*np.sin(a)))
        for a in np.linspace(1.5*np.pi,2*np.pi,7): pts.append((w/2-rad+rad*np.cos(a),zu-h/2+rad+rad*np.sin(a)))
        ch=min(rad,1.2)    # 1.2 mm : clears the corner of a USB-C overmould down to ~1 mm radius
        pts+= [(w/2,zu+h/2-ch),(w/2-ch,zu+h/2),(-w/2+ch,zu+h/2),(-w/2,zu+h/2-ch)]
        f=poly_face([(x,ya,z) for x,z in pts])
        return cq.Workplane(obj=cq.Solid.extrudeLinear(f,V(0,yb-ya,0)))
    win=prism(USB_SHELL_W+2*USB_PLAY,USB_SHELL_H+2*USB_PLAY,(USB_SHELL_H+2*USB_PLAY)/2,yi+0.5,yi-LIP-0.01)
    pocket=prism(USB_PLUG_W,USB_PLUG_H,USB_PLUG_R,yi-LIP,-OY-1)
    for c in (win,pocket): usbcut.append(c); body=body.cut(c)
    # 45 deg chamfer of the mouth, built as thin offset slices of the pocket outline
    for k in range(4):
        e=0.6*(k+1)/4; c=prism(USB_PLUG_W+2*e,USB_PLUG_H+2*e,USB_PLUG_R+e,-OY+0.6-0.6*(k+1)/4+0.15,-OY+0.6-0.6*(k+1)/4-0.01 if k<3 else -OY-1)
        usbcut.append(c); body=body.cut(c)
    if fins and USB_FINS:
        void=usbcut[0]
        for c in usbcut[1:]: void=void.union(c)
        for xc in USB_FINS:
            fin=box(xc-FIN_W/2,xc+FIN_W/2,-OY+0.7,yi-0.1,0,H).intersect(void).intersect(void.translate((0,0,-FIN_GAP)))
            upper=fin.intersect(void.translate((0,0,0.5)))
            neck=fin.intersect(box(xc-FIN_W/2,xc+FIN_W/2,-OY+0.75,-OY+1.55,0,H))
            body=body.union(upper.union(neck))
    body=body.cut(button_hole())
    if fins and BTN_FINS:
        for dy in BTN_FINS:
            yc=BY+dy
            fin=box(BX+0.1,BX+WALL-0.4,yc-FIN_W/2,yc+FIN_W/2,0,H).intersect(hole).intersect(hole.translate((0,0,-BTN_FIN_GAP)))
            upper=fin.intersect(hole.translate((0,0,0.5)))
            neck=fin.intersect(box(BX+0.5,BX+1.3,yc-FIN_W/2,yc+FIN_W/2,0,H))
            body=body.union(upper.union(neck))
    body=body.cut(flutes())
    return body.clean()
def xcyl(x0,L,d):
    return cq.Workplane(obj=cq.Solid.makeCylinder(d/2,L,V(x0,BY,BZ),V(1,0,0)))
def keys(x0,L,w,h,r_out):
    # two keys, above and below the cap (z), as boxes from the cap axis outwards
    k=None
    for sz in(-1,1):
        z0,z1=sorted([BZ+sz*(r_out-0.3),BZ+sz*(r_out+h)])
        b=box(x0,x0+L,BY-w/2,BY+w/2,z0,z1); k=b if k is None else k.union(b)
    return k
def xcone(x0,L,r0,r1):
    return cq.Workplane(obj=cq.Solid.makeCone(r0,r1,L,V(x0,BY,BZ),V(1,0,0)))
def roof(x0,L,r,hmax):
    # v4.1 : 45 deg "teardrop" roof over a horizontal round hole, cut flat at hmax above the axis
    A=r*np.sqrt(2); h=min(hmax,A-0.3); c=r/np.sqrt(2)
    pts=[(BY,BZ),(BY-c,BZ+c),(BY-(A-h),BZ+h),(BY+(A-h),BZ+h),(BY+c,BZ+c)]
    f=poly_face([(x0,y,z) for y,z in pts])
    return cq.Workplane(obj=cq.Solid.extrudeLinear(f,V(L,0,0)))
def button_hole():
    xf=BX+BACK_GAP; rp=FLANGE_R+POCKET_PLAY; rh=CAP_D/2+CAP_PLAY
    xc=xf+RIM_T                                                     # start of the cone in the pocket
    h=xcyl(BX-0.5,xc-BX+0.5,2*rp)                                   # straight part, open on the inside
    h=h.union(xcone(xc-0.001,rp-rh+0.001,rp,rh))                    # 45 deg seat
    h=h.union(xcyl(xc,OX-xc+0.5,2*rh))                              # cap hole
    h=h.union(roof(xc,OX-xc+0.5,rh,rh+KEY_H+CAP_PLAY))              # its roof prints without sagging
    h=h.union(roof(BX-0.5,xc-BX+0.5,rp,ZL-0.9-BZ))                  # same for the pocket, kept under the glass seat
    h=h.union(keys(BX-0.5,OX-BX+1.0,KEY_W+2*CAP_PLAY,KEY_H+CAP_PLAY,rh))
    h=h.union(xcone(OX-0.399,0.4,rh,rh+0.4))                        # 0.4 x 45 deg at the mouth
    return h
def make_button():
    xf=BX+BACK_GAP                                                  # back of the shoulder
    xc=xf+RIM_T; xcap=xc+(FLANGE_R-CAP_D/2)                         # end of the cone = start of the cap
    xo=OX+PROUD                                                     # outer face of the cap
    b=xcyl(xf,RIM_T,2*FLANGE_R)
    b=b.union(xcone(xc-0.001,FLANGE_R-CAP_D/2+0.002,FLANGE_R,CAP_D/2))
    b=b.union(xcyl(xcap-0.01,xo-xcap+0.01,CAP_D).edges('>X').chamfer(0.4))
    b=b.union(keys(xf,OX-xf,KEY_W,KEY_H,CAP_D/2))
    zk=KEY_Zb+ZOFF
    b=b.union(box(KEY_X+TRAVEL_GAP,xf+0.01,BY-1.6,BY+1.6,zk-1.0,zk+1.0))      # stem onto the switch
    # two clip lips on the rim, front and back (y) : a slot frees a thin tongue whose small bump
    # presses into the pocket wall and holds the button while the case is open
    for sy in(-1,1):
        b=b.cut(box(xf-0.1,xc+0.45,*sorted([BY+sy*3.55,BY+sy*3.9]),BZ-1.6,BZ+1.6))
        b=b.union(cq.Workplane(obj=cq.Solid.makeCylinder(0.4,RIM_T,V(xf,BY+sy*(FLANGE_R+POCKET_PLAY+LIP_BUMP-0.4),BZ),V(1,0,0))))
    return b.clean()
if __name__=='__main__':
    import sys
    for name,fins in (('aurapulse_case_v4',True),):
        c=make_case(fins); s=c.val(); bb=s.BoundingBox()
        print(name,'valid',s.isValid(),'solids',len(s.Solids()),'%.2f x %.2f x %.2f'%(bb.xlen,bb.ylen,bb.zlen),'vol %.1f cm3'%(s.Volume()/1000))
        cq.exporters.export(c,name+'.stl',tolerance=0.01,angularTolerance=0.1); cq.exporters.export(c,name+'.step')
    b=make_button(); s=b.val(); print('button valid',s.isValid(),'solids',len(s.Solids()))
    cq.exporters.export(b,'button_in_place.stl',tolerance=0.005,angularTolerance=0.05)
    print('H',H,'BOSS_H',BOSS_H,'usb zc',USB_SHELL_ZC+ZOFF,'btn',BX,BY,BZ)
