"""FreeCAD construction of the independent flat-front white housing variant, millimetres."""
from pathlib import Path
import math,json
import FreeCAD as A,Part
V=A.Vector
root=Path(__file__).resolve().parent;models=root.parent
def P(x,y,z):return V(x,y,z)
def rounded(w,d,rf,rb,z):
    x=w/2;y=d/2;k=math.sqrt(.5)
    outline=[
      ((-x+rf,-y),(x-rf,-y)),
      ((x-rf,-y),(x-rf+rf*k,-y+rf-rf*k),(x,-y+rf)),
      ((x,-y+rf),(x,y-rb)),
      ((x,y-rb),(x-rb+rb*k,y-rb+rb*k),(x-rb,y)),
      ((x-rb,y),(-x+rb,y)),
      ((-x+rb,y),(-x+rb-rb*k,y-rb+rb*k),(-x,y-rb)),
      ((-x,y-rb),(-x,-y+rf)),
      ((-x,-y+rf),(-x+rf-rf*k,-y+rf-rf*k),(-x+rf,-y))]
    edges=[]
    for pts in outline:
        pts=[V(a,b,z) for a,b in pts];edges.append(Part.makeLine(*pts) if len(pts)==2 else Part.Arc(*pts).toShape())
    return Part.Wire(edges)
def slab(w,d,front,back,z,h,fillet):
    solid=Part.Face(rounded(w,d,front,back,z)).extrude(V(0,0,h))
    edges=[e for e in solid.Edges if e.BoundBox.ZLength<1e-6]
    return solid.makeFillet(fillet,edges)
def cyl(r,base,h,x=0,y=0):return Part.makeCylinder(r,h,V(x,y,base))
def rect(x,z,w,h,f,b,r):
    s=Part.makeBox(w,b-f,h,V(x-w/2,f,z-h/2))
    edges=[e for e in s.Edges if e.BoundBox.YLength>b-f-1e-5 and e.BoundBox.XLength<1e-6 and e.BoundBox.ZLength<1e-6]
    return s.makeFillet(r,edges)
def ycyl(r,f,b,x,z):return Part.makeCylinder(r,b-f,V(x,f,z),V(0,1,0))
def remain(shape,blank,id):
    assert shape.isValid() and len(shape.Solids)==1,id
    samples=[]
    # Qualify a triangle against the original, uncut outer stock to keep dielectric
    # finish off cut interface walls, gasket seats, bores, threads and airflow paths.
    ext=[f for f in blank.Faces if f.BoundBox.ZLength>1e-4]
    for face in shape.Faces:
        vs,fs=face.tessellate(.023);a,b,c=[vs[i] for i in fs[len(fs)//2]]
        mid=(a+b+c)/3
        point=Part.Vertex(mid)
        surface='outer' if any(f.distToShape(point)[0]<.035 for f in ext) else 'internal'
        if id=='C02' and -8.85<mid.x<8.85 and 58.58<mid.z<76.62 and -11.205<mid.y<-10.575:
            surface='outer'
        samples.append(dict(surface=surface,v=[[round(x,6) for x in v] for v in vs],f=fs))
    shape.exportStep(str(root/(id+'.step')))
    results[id]=samples;solids[id]=shape
w=25.;d=22.4;rf=2.85;rb=5.2
results={};solids={}
blank=slab(w,d,rf,rb,3,50.45,.45)
grip=blank.cut(cyl(9,2.9,50.7))
# Restore the service sole mounting lugs from R01 inside the common bore.
old=Part.read(str(models/'r01/chassis/C01.step'))
grip=grip.fuse(old.common(cyl(9.02,3,1.22)))
import runpy
grip=runpy.run_path(str(root/'display/mechanics.py'))['bay'](grip)
remain(grip.removeSplitter(),blank,'C01')
# Upper shoulder tapers back to the round mouthpiece interface.
shoulder=Part.makeLoft([rounded(w,d,rf,rb,77.5),rounded(24.86,22.30,3.0,5.3,79.5),
                        rounded(23.05,21.55,6,7,82.5),rounded(21.20,20.95,9.1,9.4,84.9),
                        rounded(20.88,20.88,10.40,10.40,86)],True,False)
solid=Part.Face(rounded(w,d,rf,rb,54.15)).extrude(V(0,0,23.35)).fuse(shoulder).removeSplitter()
upper=solid.cut(cyl(9,54.05,30.35)).cut(cyl(7.10,84.4,2))
for y in (-8,8):upper=upper.cut(cyl(.50,84.35,1.75,0,y))
for sign in (-1,1):
 x=7.8*sign
 upper=upper.cut(Part.makeBox(1.8,1.36,1.85,V(min(x,sign*6),-.68,84.3)).fuse(cyl(.68,84.3,1.85,x)))
upper=upper.cut(Part.makeCylinder(.42,14,V(0,0,55.18),V(0,-1,0)))
# A blind field in the front wall, adapted from the CJ cube's framed face.
# Round the two rims after machining to give a physical highlight at grazing angles.
field=rect(0,67.6,17.4,17.6,-11.48,-10.88,.68)
upper=upper.cut(field)
def round_field_edges(shape,at,limit,fillet):
    edges=[e for e in shape.Edges if abs(e.BoundBox.YMin-at)<1e-5 and abs(e.BoundBox.YMax-at)<1e-5
           and e.BoundBox.XMin>=-8.71 and e.BoundBox.XMax<=8.71
           and e.BoundBox.ZMin>=limit[0] and e.BoundBox.ZMax<=limit[1]]
    assert edges,(at,limit)
    return shape.makeFillet(fillet,edges)
upper=round_field_edges(upper,-11.2,(58.79,76.41),.12)
upper=round_field_edges(upper,-10.88,(58.79,76.41),.08)
for j in range(7):
    upper=upper.cut(rect(-3.35,68.5+j*.93,8.50,.43,-11.1,-10.62,.195))
upper=upper.cut(rect(0,66.88,15.86,.25,-11.0,-10.74,.105))
# Both lips on each slot and the engraved dividing channel are rounded.
upper=round_field_edges(upper,-10.88,(66.70,74.37),.035)
upper=round_field_edges(upper,-10.62,(68.25,74.37),.035)
for z in [68.5+j*.93 for j in range(7)]:
    assert upper.isInside(V(-3.35,-10.60,z),1e-6,True)
    assert not upper.isInside(V(-3.35,-10.63,z),1e-6,True)
remain(upper.removeSplitter(),solid,'C02')
b=slab(24.80,22.2,rf,rb,53.45,.7,.11)
remain(b.cut(cyl(9.85,53.4,.9)),b,'C03')
# Add rectangular external stock around the service sole; preserve the exact
# original USB aperture and two counterbored service fasteners.
b=slab(24.85,22.28,rf,rb,0,3,.44)
old=Part.read(str(models/'r01/chassis/C07.step'))
sole=b.cut(cyl(8.90,-.1,3.2)).fuse(old.common(cyl(8.91,0,3))).removeSplitter()
sole=runpy.run_path(str(root/'environment/sole.py'))['make'](sole)
remain(sole,b,'C07')
for i,a in enumerate(solids):
 for b in list(solids)[i+1:]:assert solids[a].common(solids[b]).Volume<1e-5,(a,b)
for f in (root/'display').glob('DISP-*.step'):
    dpart=Part.read(str(f));assert solids['C01'].common(dpart).Volume<1e-5,f
(root/'housing-mm.json').write_text(json.dumps(results,separators=(',',':')))
print({k:round(s.Volume,2) for k,s in solids.items()})
