"""Photo-supported broad floor wells/beads; all pressing dimensions estimated."""
from pathlib import Path
import copy,hashlib,json
import cadquery as cq

ROOT=Path(__file__).resolve().parent
SOURCE='rear-cabin-step-reference'
OUTPUT='formed-floor-reference'
S=2032/2.4
Y=.35*S
T=1.5
data=json.loads((ROOT/(SOURCE+'.json')).read_text())
a=cq.Assembly.importStep(str(ROOT/(SOURCE+'.step')))
native={n:o.obj for n,o in a.objects.items()if o.obj is not None}
def rounded(w,l,r,x,y,z):
    wire=cq.Workplane('XZ',origin=(x,y,z)).rect(w,l).val()
    return wire.fillet2D(r,wire.Vertices())
features=[dict(role='front_well',x=435.,z=75.,width=190.,length=350.,inset=15.,depth=8.,radius=12.)]
features += [dict(role='transverse_bead',x=365.,z=z,width=310.,length=24.,inset=5.,depth=3.,radius=10.) for z in [-170.,-280.,-390.,-500.,-610.]]
voids=[]
for f in features:
    w,l,r,x,z=f['width'],f['length'],f['radius'],f['x'],f['z']
    wires=[rounded(w,l,r,x,Y+5,z),rounded(w,l,r,x,Y,z),
           rounded(w-2*f['inset'],l-2*f['inset'],min(r, (l-2*f['inset'])/2-.1),x,Y-f['depth'],z)]
    voids.append(cq.Solid.makeLoft(wires,ruled=True))
changes={}
for side,sign in [('left',1),('right',-1)]:
    name='cabin_'+side+'_floor_with_retained_seat_bores_reference'
    old=native[name];bb=old.BoundingBox()
    solid=cq.Solid.makeBox(bb.xlen,30,bb.zlen,(bb.xmin,Y-30,bb.zmin))
    for void in voids:solid=solid.cut(void if sign>0 else void.mirror('YZ'))
    # Difference of vertically translated subgraphs gives a constant projected
    # Y section over the whole height field, with genuinely open undersides.
    skin=solid.cut(solid.translate((0,-T,0)))
    masks=[]
    for face in cq.Workplane(obj=old).faces('>Y').vals():
        masks.append(cq.Solid.extrudeLinear(face.outerWire(),face.innerWires(),(0,-30,0)).translate((0,1,0)))
    skin=skin.intersect(cq.Compound.makeCompound(masks)).clean()
    assert skin.isValid()and all(s.Volume()>0 for s in skin.Solids())
    changes[name]=skin
limits=('AHA7202/HMP415032 replacement photographs support recessed front floor wells and transverse pressed channels, not fitted dimensions or a traced stamping. '
        'The 190x350mm well,8mm depth,five310x24mm bead envelopes,3mm depth,radii,stations and mirrored opposite side are construction estimates. '
        'The1.5mm section is an exact projected-Y skin in this drawing, not verified normal metal gauge or sheet development. '
        'Original floor outlines,eight seat bores,hanger pockets and rail passages remain the cutting mask; existing openings can interrupt a bead. '
        'No extra drains,plugs,reinforcement pads or factory hole identities are assigned. '
        'All seat,mount,body,gearbox and axle poses stay. Native material/section checks do not establish fitted pressing identity,seat support,strength,loaded clearances or a replacement path. '
        'The forward gearbox/floor registration conflict is not corrected by this architecture change.')
revision=dict(evidence='formed-floor-evidence.json',owner_dimensions_applied=False,
              selected_left_features_mm=features,right_mirrored=True,projected_y_gauge_mm=T,
              retained_floor_plane_y_mm=Y,limits=limits,
              source_sha256={e:hashlib.sha256((ROOT/(SOURCE+e)).read_bytes()).hexdigest()for e in ['.json','.step']})
result=copy.deepcopy(data);out=cq.Assembly(name='formed_floor_architecture')
for part in result['parts']:
    n=part['name'];shape=changes.get(n,native[n]);out.add(shape,name=n,color=cq.Color(*part['color']))
    if n in changes:
        vs,ts=shape.tessellate(.3,.12)
        part['vertices']=[round(v,4)for p in vs for v in p.toTuple()];part['triangles']=[v for t in ts for v in t]
result['formed_floor_revision']=revision;result['limits']+=' '+limits
out.export(str(ROOT/(OUTPUT+'.step')))
p=ROOT/(OUTPUT+'.step');p.write_text('\n'.join(l.rstrip()for l in p.read_text().splitlines())+'\n')
check=cq.importers.importStep(str(p)).val();assert check.isValid()and all(s.Volume()>0 for s in check.Solids())
(ROOT/(OUTPUT+'.json')).write_text(json.dumps(result,separators=(',',':'))+'\n')
print(json.dumps(dict(groups=len(result['parts']),valid_positive_solids=len(check.Solids()),changed=list(changes))))
