"""XIAO nRF52840 Sense radio-style clip-on mic enclosure, parametric CAD.
Generate 3D-print-ready STL pieces and editable STEP CAD with CadQuery 2.x.
Rev 2: tighter XIAO side guides, front/rear PCB end stops and optional shims for old print.
Concept prototype: verify component and soldered-wire dimensions before fitting battery.
License: CC0. Units: mm.
"""
import cadquery as cq
from cadquery import Vector as V
from pathlib import Path
import math

OUT=Path(__file__).resolve().parent
# Dimensions measured from supplier data sheets; case dimensions are designed allowances.
CASE_W=40.0
CASE_H=82.0
BACK_DEPTH=14.0
LID_DEPTH=4.0
WALL=2.1
CORNER_R=6.0
FLOOR=2.2
BATT_W=30.0   # User-measured battery: 37 x 30 x 6 mm, 30 across the case
BATT_L=37.0   # 37 mm along case long axis
BATT_T=6.0
BOARD_W=17.8
BOARD_L=21.0
BATT_Y=9.0
BOARD_Y=-27.0
BUTTON_Y=13.0
BUTTON_YS=(-2.0,13.0,28.0)
BUTTON_BODY=12.0
BUTTON_CLEARANCE=0.35
SCREWS=[(sx*14.0,sy*34.7) for sx in [-1,1] for sy in [-1,1]]


def rounded_block(w,h,depth,r,z=0,xy=(0,0)):
    s=cq.Workplane('XY').rect(w,h).extrude(depth).edges('|Z').fillet(r).val()
    return s.translate((xy[0],xy[1],z))

def box(w,h,d,cx=0,cy=0,cz=0):
    return cq.Workplane('XY').box(w,h,d).val().translate((cx,cy,cz))

def cyl(r,h,x,y,z,direction=(0,0,1)):
    return cq.Solid.makeCylinder(r,h,V(x,y,z),V(*direction))

# ----------------- REAR SHELL ----------------------------------------------
back=rounded_block(CASE_W,CASE_H,BACK_DEPTH,CORNER_R)
# Open cavity from the front, rounded corners.
inner=rounded_block(CASE_W-2*WALL,CASE_H-2*WALL,BACK_DEPTH-FLOOR+.25,CORNER_R-WALL,FLOOR)
back=back.cut(inner)
# Flat-floor adhesive locating rails for 37 x 30 x 6 mm battery; rails are NOT clamps on LiPo pouch.
for x in (-16.3,16.3):
    back=back.fuse(box(1.1,BATT_L,3.3,x,BATT_Y,FLOOR+1.65))
# Front and rear stops keep battery physically away from module and connector.
for y in (-10.6,28.6):
    back=back.fuse(box(16,1.1,1.35,0,y,FLOOR+.675))
# PCB bed support, two slotted channels along edges; lightly tape module to four bearing pads.
for x in (-7.7,7.7):
    for y in (-35.3,-19.0):
        back=back.fuse(box(3.1,3.25,5.4,x,y,FLOOR+2.7))
# side guides next to the XIAO PCB, not on top of electrical pads
# PCB nominal width 17.8 mm. Rev 1 had 19.5 mm between guides (0.85 mm/side).
# Rev 2: guide inner edges at +/- 9.25 -> 18.5 mm channel (0.35 mm/side).
# The guides touch only the *edge*, not PCB pads; do not force-fit if headers/wires installed.
PCB_SIDE_CLEARANCE = 0.35
for x in (-(BOARD_W/2 + PCB_SIDE_CLEARANCE + 1.0),
           +(BOARD_W/2 + PCB_SIDE_CLEARANCE + 1.0)):
    for y in (-32.0,-21.6):
        back=back.fuse(box(2.0,4.3,6.3,x,y,FLOOR+3.15))
# Fore/aft end stops: 0.30 mm free space at both ends of the 21 mm board.
# Paired tabs clear the centered USB connector and avoid the microphone/pads.
for x in (-6.3,6.3):
    back=back.fuse(box(2.0,0.8,6.25,x,-38.2,FLOOR+3.125))
    back=back.fuse(box(2.0,0.8,6.25,x,-15.8,FLOOR+3.125))
# Four M3 screw pillars; lid holes are through, posts are blind 2.55 mm pilots.
for x,y in SCREWS:
    back=back.fuse(cyl(3.50,11.8,x,y,FLOOR))
    back=back.cut(cyl(1.275,9.4,x,y,4.8))
# USB-C connector / cable cutout in bottom edge of back (XIAO rotated 180 degrees)
back=back.cut(box(11.5,8.0,7.0,0,-39.6,10.2))
# Rev3: no side switch holes. Three 12x12 mm buttons relocated to front face.
# Side-mounted 12x12 switches would collide with the 30 mm wide battery envelope.
# Power slide switch slot on left; exact purchasable slider model TBD.
back=back.cut(box(8,10.5,3.2,-19.0,19.0,9.0))
# Two mounting holes for clip from INNER floor downward, with shallow head recess.
# Keep screw heads below the protective battery shelf and cover screw heads with insulation tape.
CLIP_SCREWS=[(-5.6,31.0),(5.6,31.0)]
for x,y in CLIP_SCREWS:
    back=back.cut(cyl(1.65,5.0,x,y,-.5))
    back=back.cut(cyl(3.15,.85,x,y,FLOOR-.82))

# ----------------- FRONT SHELL ---------------------------------------------
front=rounded_block(CASE_W,CASE_H,LID_DEPTH,CORNER_R,z=BACK_DEPTH)
# Edge fit ribs only between screw pillars.
for x in (-16.95,16.95):
    front=front.fuse(box(1.15,48.0,1.55,x,0,13.225))
for y in (-37.05,37.05):
    front=front.fuse(box(19.0,1.12,1.55,0,y,13.225))
# M3 front through holes 3.30 mm, pan-head counterbore 6.2 mm x 1.5 mm.
for x,y in SCREWS:
    front=front.cut(cyl(1.65,5.0,x,y,13.0))
    front=front.cut(cyl(3.10,1.55,x,y,16.5))
# Three 12x12 mm 4-pin tactile buttons on the front face, 15mm vertical pitch.
# They sit in separate underside pockets, NOT against the LiPo pouch.
# Button cap plunger has an 8mm opening and inner 11mm flange so it is captured.
# Keep 12.7mm square switch clearance; confirm actual switch height and pin geometry.
for cy in BUTTON_YS:
    front=front.cut(cyl(4.00,4.5,0,cy,13.75))
    front=front.cut(cyl(5.65,1.50,0,cy,13.85))
    # Square retaining ring: outer 15.5 mm, inner 12.7 mm, 2.5 mm depth.
    ring=box(15.5,15.5,2.45,0,cy,12.775).cut(box(12.70,12.70,2.65,0,cy,12.775))
    front=front.fuse(ring)
# mic inlet directly over flipped board microphone; see assembly orientation in README.
for x in (-9.3,-6.8,-4.3):
    for y in (-21.8,-19.3,-16.8):
        front=front.cut(cyl(.72,5,x,y,13.5))
# small indicator light hole for optional LED, not connected by default
front=front.cut(cyl(1.15,4.8,8.0,-23.0,13.5))
# Decorative grip lines removed to clear bottom tactile switch.

# ----------------- THREE IDENTICAL FRONT PUSH ACTUATORS --------------------
# Print 3 of the same cap, introduced from back before mounting tactile switches.
# Visible Ø7.5 mm plunger, flange Ø10.8 mm. Test button travel before bonding.
main_btn=cyl(5.40,1.2,0,0,14.15)
main_btn=main_btn.fuse(cyl(3.72,3.5,0,0,15.15))
main_btn=main_btn.fuse(cyl(1.6,0.6,0,0,13.6))
try:
    main_btn=cq.Workplane(obj=main_btn).edges('>Z').fillet(.35).val()
except Exception:
    pass

# ----------------- REAR CLIP (FLEXIBLE, PETG) -------------------------------
# Attached using two M3 screws from inside shell, into M3 nuts in the clip mount.
# Arm extruded across X, bent near the anchor. Gap to back shell for garment.
# Coordinate side profile in Y/Z; anchored at y~+27, tongue reaches y~-25.
# mount plate: z negative is BACK of device.
clip_base=rounded_block(20.5,16.0,3.6,2.2,z=-3.6,xy=(0,29.5))
# Long arm trapezoid side silhouette. Workplane YZ extrude across x.
# Y coordinate approx from -25 to +23, Z negative moves away from user's device.
section=[(-26.0,-4.0),(-24.0,-6.0),(18.0,-7.8),(23.3,-7.8),
         (25.3,-5.4),(25.3,-2.50),(22.7,-2.5),(21.6,-5.5),
         (18.0,-5.7),(-22.0,-4.2),(-24.0,-2.95)]
arm=(cq.Workplane('YZ',origin=(-7.35,0,0)).polyline(section).close().extrude(14.7).val())
clip=clip_base.fuse(arm)
# M3 captive nut hex sockets on underside of clip mount and screw holes.
for x,y in CLIP_SCREWS:
    clip=clip.cut(cyl(1.65,5.0,x,y,-3.8))
    # hex pocket for M3 nut, approx 5.7 mm across flats and 2.65 mm deep
    nut=(cq.Workplane('XY').polygon(6,6.60).extrude(2.65).val()
         .translate((x,y,-3.61)))
    clip=clip.cut(nut)


# Side actuators removed in Rev3: all three tactile buttons are front-mounted.
# ----------------- RETROFIT SHIMS FOR OLD M3 PRINT ------------------------
# Standalone flat plates: print 2 pieces of one chosen thickness. Install with
# thickness across X, long side along board Y and height vertical. Use a little
# Kapton or low-outgassing neutral-cure adhesive only where safe, never over mic.
# Revision 1 guide gap was 0.85 mm per side. Start with the 0.5 or 0.7 plate.
retrofit_shims = {}
for t in (0.50,0.70,0.90):
    shim = cq.Workplane('XY').box(15.0, 1.5, t, centered=(True,True,False)).val()
    retrofit_shims[f'06_eski_kasa_yan_sim_{str(t).replace(".","_")}mm_x2'] = shim

# ----------------- OPTIONAL MOCKUP SPACERS --------------------------------
# NOT printable parts. Included only in STEP reference as separate solids.
# The real XIAO dimensions may differ with presoldered pin headers! No headers assumed.
board_ref=rounded_block(BOARD_W,BOARD_L,1.15,1.05,z=7.6,xy=(0,BOARD_Y))
battery_ref=rounded_block(BATT_W,BATT_L,BATT_T,1.9,z=FLOOR,xy=(0,BATT_Y))

parts={
    '01_arka_govde':back,
    '02_on_kapak':front,
    '03_on_tus_kapagi_3_adet':main_btn,
    '04_yaka_klipsi_PETG':clip,
}
for name,obj in parts.items():
    stl=OUT/(name+'.stl')
    cq.exporters.export(obj,str(stl),tolerance=.06,angularTolerance=.12)
    print(f'{name}: {stl.stat().st_size:,} B; {obj.BoundingBox().xlen:.2f}x{obj.BoundingBox().ylen:.2f}x{obj.BoundingBox().zlen:.2f}; solids={len(obj.Solids())}; vol={obj.Volume():.1f} mm3')
# full editable assembly for FreeCAD, Fusion 360, Onshape (STEP), with body and lids installed.
assembly=cq.Assembly(name='YakaMikrofonu')
for name,ob,color in [
    ('arka_govde',back,cq.Color(.16,.19,.23)),
    ('on_kapak',front,cq.Color(.28,.32,.37)),
    *[(f'on_tus_{j+1}',main_btn.translate((0,y,0)),cq.Color(.08,.10,.11)) for j,y in enumerate(BUTTON_YS)],
    ('yaka_klips',clip,cq.Color(.2,.2,.22)),
    ('XIAO_reference',board_ref,cq.Color(.02,.12,.17,.35)),
    ('Battery_reference',battery_ref,cq.Color(.8,.65,.2,.25)),
]:
    assembly.add(ob,name=name,color=color)
assembly.save(str(OUT/'YakaMikrofonu_montaj.step'))
print('STEP generated')
