"""Missing outer heelboard/shut panel; no inferred hanger/body registration."""
from pathlib import Path
import copy,hashlib,json,math
import cadquery as cq

ROOT=Path(__file__).resolve().parent
SOURCE='formed-floor-reference'
OUTPUT='rear-shut-panel-reference'
S=2032/2.4
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}
inner=native['cabin_lower_heelboard_with_tunnel_mouth_reference']
raised=native['cabin_raised_rear_cockpit_floor_to_boot_comparison']
Z=inner.BoundingBox().zmin-50.0
TOP=raised.BoundingBox().ymin
BOTTOM=.27*S
T=1.5
RETURN=16.0
P=lambda x,y:cq.Vector(x,y,Z)

# The existing stepped body-width construction remains the outline reference.
# It is not calibrated by the replacement photographs or assigned a seam map.
outline=[[-.66*S,BOTTOM],[.66*S,BOTTOM],[.66*S,.39*S],
         [.47*S,.39*S],[.47*S,TOP],[-.47*S,TOP],
         [-.47*S,.39*S],[-.66*S,.39*S]]
points=[P(*p) for p in outline]
panel=cq.Solid.extrudeLinear(cq.Wire.makePolygon(points+[points[0]]),[],(0,0,T))
topreturn=cq.Solid.makeBox(.94*S,T,RETURN,(-.47*S,TOP-T,Z))
lowerreturn=cq.Solid.makeBox(1.32*S,T,RETURN,(-.66*S,BOTTOM,Z))
panel=panel.fuse(topreturn,lowerreturn)

# Central arched passage and two lower notches are visible topology in BMH8006.
# Numerical sizes and notch X centers are explicitly selected, not fitted maps.
R=90.0
SPRING=430.0
edges=[cq.Edge.makeLine(P(-R,BOTTOM-5),P(R,BOTTOM-5)),
       cq.Edge.makeLine(P(R,BOTTOM-5),P(R,SPRING)),
       cq.Edge.makeThreePointArc(P(R,SPRING),P(0,SPRING+R),P(-R,SPRING)),
       cq.Edge.makeLine(P(-R,SPRING),P(-R,BOTTOM-5))]
central=cq.Solid.extrudeLinear(cq.Wire.assembleEdges(edges),[],(0,0,RETURN+10)).translate((0,0,-5))
panel=panel.cut(central)
notches=[]
for sign in [-1,1]:
    cx=sign*.48*S;half=50.;height=70.;radius=6.;y=BOTTOM+height;k=math.sqrt(.5)
    # Rounded upper corners; bottom opens below the lower return.
    pts=[P(cx-half,BOTTOM-5),P(cx+half,BOTTOM-5),P(cx+half,y-radius)]
    es=[cq.Edge.makeLine(pts[0],pts[1]),cq.Edge.makeLine(pts[1],pts[2]),
        cq.Edge.makeThreePointArc(pts[2],P(cx+half-radius+radius*k,y-radius+radius*k),P(cx+half-radius,y)),
        cq.Edge.makeLine(P(cx+half-radius,y),P(cx-half+radius,y)),
        cq.Edge.makeThreePointArc(P(cx-half+radius,y),P(cx-half+radius-radius*k,y-radius+radius*k),P(cx-half,y-radius)),
        cq.Edge.makeLine(P(cx-half,y-radius),pts[0])]
    tool=cq.Solid.extrudeLinear(cq.Wire.assembleEdges(es),[],(0,0,RETURN+10)).translate((0,0,-5))
    panel=panel.cut(tool)
    notches.append(dict(center_x_mm=cx,width_mm=100,height_mm=height,upper_radius_mm=radius))
panel=panel.clean()
assert panel.isValid() and len(panel.Solids())==1
limits=('BMH8005/8006 and first-hand factory photograph BK support two separate parallel rear-bulkhead panels, '
        'with a central arched passage and lower side notches in the outer shut panel. '
        'The50mm spacing behind the retained inner heelboard,stepped outline,1.5mm projected-Z gauge,16mm returns, '
        '180mm central width,430mm spring-line height and100x70mm lower notches are construction estimates. '
        'Notch X centers repeat existing hanger lateral references without establishing a fitted connection. '
        'The upper return contacts the existing raised floor underside in this drawing only;sheet/seam ownership is unknown. '
        'The retained front spring eye atZ=-.54 and inner heelboard atZ=-.83 remain unregistered. '
        'No support bridge,extended hanger box,receiver hole,captive nut,angle reinforcement,weld schedule or loaded support is inferred. '
        'AHA7210 is a separate angle-shaped reinforcement role,not identification of the existing generic body box. '
        'All original floor/tunnel/heelboard/sill and spring/seat/body/mechanical source poses remain. '
        'Source contacts are drawing discrepancies,not proof of actual interference or clearance. '
        'No body alignment,bracing,cutting/welding,repair suitability or verified replacement/removal path.')
revision=dict(evidence='rear-shut-panel-evidence.json',owner_dimensions_applied=False,
              estimated_inner_outer_spacing_mm=50.,inner_rear_face_z_mm=inner.BoundingBox().zmin,
              estimated_shut_panel_front_face_z_mm=Z+T,estimated_shut_panel_rear_face_z_mm=Z,
              estimated_projected_z_gauge_mm=T,estimated_returns_depth_mm=RETURN,
              selected_outline_xy_mm=outline,selected_bottom_y_mm=BOTTOM,retained_floor_underside_y_mm=TOP,
              estimated_central_arch=dict(half_width_mm=R,spring_line_y_mm=SPRING,top_y_mm=SPRING+R),
              selected_lower_notches=notches,
              unsupported_hanger_connection=dict(eye_z_mm=-.54*S,inner_panel_z_mm=inner.BoundingBox().zmax,
                                                  axial_station_difference_mm=abs(inner.BoundingBox().zmax+.54*S)),
              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='cabin_with_separate_outer_heelboard_shut_panel')
for p in result['parts']:
    out.add(native[p['name']],name=p['name'],color=cq.Color(*p['color']))
name='cabin_outer_rear_bulkhead_shut_panel_comparison'
color=[.27,.35,.24]
out.add(panel,name=name,color=cq.Color(*color))
vs,ts=panel.tessellate(.1,.12)
result['parts'].append(dict(name=name,color=color,vertices=[round(v,4)for p in vs for v in p.toTuple()],triangles=[v for t in ts for v in t]))
result['rear_shut_panel_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')
(ROOT/(OUTPUT+'.json')).write_text(json.dumps(result,separators=(',',':'))+'\n')
restored=cq.importers.importStep(str(p)).val()
assert restored.isValid()and len(restored.Solids())==23 and all(s.Volume()>0 for s in restored.Solids())
print(json.dumps(dict(groups=14,valid_positive_solids=23,added_connected_shut_panel=True,held_meshes=13)))
