"""Build nominal fluid-path concepts. Run using FreeCAD's Python with its lib on PYTHONPATH."""
import csv, math
from pathlib import Path
import FreeCAD as A, Part, MeshPart
V=A.Vector
root=Path(__file__).resolve().parent
for sub in ('step','stl'): (root/sub).mkdir(exist_ok=True)
doc=A.newDocument("Fluid")
parts=[]
def cyl(r,z,h,x=0,y=0):
    return Part.makeCylinder(r,h,V(x,y,z))
def ring(ro,ri,z,h,x=0,y=0):
    return cyl(ro,z,h,x,y).cut(cyl(ri,z-.01,h+.02,x,y))
def torus(r,t,z,x=0):
    return Part.makeTorus(r,t,V(x,0,z))
def solid(code,name,material,group,s):
    s=s.removeSplitter()
    assert s.isValid() and len(s.Solids)==1 and s.Volume>0,code
    o=doc.addObject('Part::Feature',code); o.Label=name; o.Shape=s
    Part.export([o],str(root/'step'/f'{code}.step'))
    mesh=MeshPart.meshFromShape(Shape=s,LinearDeflection=.048,AngularDeflection=.18,Relative=False)
    assert mesh.isSolid(), code
    mesh.write(str(root/'stl'/f'{code}.stl'))
    parts.append((code,name,material,group,s))
def piston(x,group,prefix,bore,z):
    # Installed equivalent ellipse preserves the section area of the 0.95 mm free ring.
    depth,width,free=.80,1.25,.95
    body=cyl(bore-.10,z,.85,x).fuse(cyl(bore-depth,z+.85,width,x)).fuse(cyl(bore-.10,z+.85+width,.85,x))
    solid(prefix+'P',group+' follower piston','PEEK candidate',group,body)
    center=z+.85+width/2
    pts=[V(x+bore-depth/2+depth/2*math.cos(i*math.tau/96),0,center+free**2/(2*depth)*math.sin(i*math.tau/96)) for i in range(96)]
    section=Part.Face(Part.makePolygon(pts+[pts[0]]))
    solid(prefix+'S',group+' installed piston seal','elastomer candidate',group,section.revolve(V(x,0,0),V(0,0,1),360))
g='Primary reservoir'
solid('F01','Precision barrel','borosilicate candidate',g,ring(7,6,57,25))
solid('F02','Atmospheric end plate','316L candidate',g,ring(7,.65,56,1).fuse(ring(5.98,.65,57,.8)))
piston(0,g,'F03',6,59.5)
cap=cyl(5.97,81,1).fuse(cyl(7,82,2)).fuse(cyl(1.60,84,2)).cut(cyl(.60,80.8,5.4)).cut(cyl(1.35,80.8,1.8,3.7)).cut(cyl(1.65,82.6,1.6,3.7))
cap.rotate(V(0,0,0),V(0,0,1),90)
solid('F04','Dual-port manifold','316L candidate',g,cap)
solid('F05','Refill septum','elastomer candidate',g,cyl(1.64,82.6,.95,0,3.7))
solid('F06','Septum retaining bezel','316L candidate',g,cyl(1.64,83.55,.45,0,3.7).cut(cyl(1.20,83.5,.6,0,3.7)).cut(Part.makeCone(1.20,1.43,.23,V(0,3.7,83.77))))
# Cartridge ends require qualified joints to barrel.
g='Refill bottle'
x=48
solid('F10','Closed-transfer refill barrel','borosilicate candidate',g,ring(10,8.8,10,34,x))
piston(x,g,'F11',8.8,15)
solid('F12','Refill follower rear stop','316L candidate',g,ring(10,1,9,1,x))
# Compact circular bayonet base clears the reservoir boss when inverted for refill.
base=cyl(10,44,2,x).fuse(cyl(3.25,46,.85,x))
for dx in (-3.35,3.35):
    base=base.fuse(Part.makeBox(.76,.68,.33,V(x+dx-.38,-.34,46.30)))
head=base.fuse(cyl(1.50,46.85,2.15,x)).fuse(cyl(1.05,49,.30,x)).cut(cyl(.61,43.8,5.7,x))
solid('F13','Transfer nose with guided pilot and bayonet lugs','316L candidate',g,head)
solid('F14','Hollow transfer tip','316L candidate',g,ring(.60,.35,46,4.85,x))
cx=64
cover=cyl(4.18,46,6.25,cx).cut(cyl(3.34,45.9,5.60,cx))
for angle in (0,180):
    entry=Part.makeBox(1.3,.91,.75,V(cx+3.2,-.455,45.95))
    entry.rotate(V(cx,0,0),V(0,0,1),angle)
    path=Part.makeCylinder(4.45,.51,V(cx,0,46.21),V(0,0,1),58)
    path.rotate(V(cx,0,0),V(0,0,1),angle-8)
    cover=cover.cut(entry).cut(path)
solid('F15','Quarter-turn transport cover, parked beside bottle','engineering polymer candidate',g,cover)
# Locked cap transformed onto the fill nose; verify nominal non-interference.
installed=cover.copy()
installed.translate(V(x-cx,0,0)); installed.rotate(V(x,0,0),V(0,0,1),-36)
assert installed.common(head).Volume<1e-5
assert installed.common(parts[-2][4]).Volume<1e-5
solid('F16','Refill plunger stem','PEEK candidate',g,cyl(.90,5,10,x).fuse(cyl(5,4,1,x)))
# Alternative vented cartridge: top vent and central outlet geometries.
g='Vented reference'; x=80
solid('F20','Rigid reference barrel','borosilicate candidate',g,ring(7,6,57,26,x))
solid('F21','Reference bottom closure','316L candidate',g,cyl(7,56,1,x))
head=cyl(7,83,1,x).fuse(cyl(1.6,84,2,x)).cut(cyl(.6,82.9,3.2,x)).cut(cyl(.50,82.9,1.2,x+3.7))
solid('F22','Vented head and outlet','316L candidate',g,head)
# Alternative flexible corrugated wall, represented as formed steady-state envelope.
g='Collapsible candidate'; x=105
def profile(coords):
    points=[V(x+r,0,z) for r,z in coords]
    return Part.Face(Part.makePolygon(points+[points[0]])).revolve(V(x,0,0),V(0,0,1),360)
wall=[(4.8,58)]+[(5.9 if i%2==0 else 4.8,59+i) for i in range(22)]+[(4.8,81.5)]
solid('F30','Corrugated variable-volume liner','flexible barrier material TBD',g,profile(wall+[(r-.24,z) for r,z in reversed(wall)]))
solid('F31','Liner bottom disk','compatible barrier material TBD',g,cyl(4.8,57.6,.4,x))
solid('F32','Liner manifold and outlet','contact polymer TBD',g,ring(4.8,.60,81.5,1,x).fuse(ring(1.6,.60,82.5,3.5,x)))
solid('F33','Vented guard sleeve','316L candidate',g,ring(7,6.2,56,27,x).cut(Part.makeCylinder(1.6,15,V(x-7.5,0,61),V(1,0,0))))
with (root/'manifest.csv').open('w',newline='') as f:
    w=csv.writer(f); w.writerow(('id','name','material','group','file'))
    for code,name,mat,group,s in parts: w.writerow((code,name,mat,group,'stl/'+code+'.stl'))
checks=[]
for i,(code,_,_,group,s) in enumerate(parts):
    for d,_,_,h,t in parts[:i]:
        if h!=group: continue
        v=s.common(t).Volume
        assert v<1e-5,(code,d,v)
groupbox=A.BoundBox()
for c,_,_,g,s in parts:
    if g=='Primary reservoir': groupbox.add(s.BoundBox)
assert abs(groupbox.XLength-14)<1e-5 and abs(groupbox.ZMin-56)<1e-5 and abs(groupbox.ZMax-86)<1e-5
# Fully docked refill nose: turn the refill assembly over, shoulder meets z84.
docked=head.copy(); docked.rotate(V(48,0,49),V(1,0,0),180); docked.translate(V(-48,3.7,84-49))
for key in ('F04','F06'):
    fixed=next(p[4] for p in parts if p[0]==key)
    assert docked.common(fixed).Volume<1e-5,(key,'docking interference')
# Nominal clearance from the installed chassis and bounds of both power lead jogs.
chassis_file=root.parent/'chassis'/'C02.step'
if chassis_file.is_file():
    sleeve=Part.read(str(chassis_file))
    assert docked.common(sleeve).Volume<1e-5
for sign in [-1,1]:
    pad_and_jog=Part.makeBox(4.7,1.7,1.68,V(3.7 if sign>0 else -8.4,-.85,84.32))
    assert docked.common(pad_and_jog).Volume<1e-5
assert abs((6-.8)-5.2)<1e-9
doc.recompute()
doc.saveAs(str(root/'Fluid.FCStd'))
(root/'checks.txt').write_text(f'{len(parts)} single-solid valid B-reps; {len(parts)} closed meshes; no within-group positive-volume clashes above 0.00001 mm3. Primary OD14, z56..86 mm. Locked F15 clears F13 and F14. Fully docked F13 clears F04, F06 and power-interface gauge boxes. C02 checked when present. Nominal seal squeeze 15.8%, area fill 70.9%.\n')
