"""Build shared analytic snack-bin geometry and source-guided B/D reliefs in FreeCAD."""
import sys, json, math, hashlib
from pathlib import Path
sys.path.insert(0,"/Applications/FreeCAD.app/Contents/Resources/lib")
import FreeCAD as A, Part
V=A.Vector
ROOT=Path(__file__).resolve().parent.parent
sys.path.insert(0,str(ROOT.parents[2]/'models/modular-drawer/latest/Source'))
from step_units import ensure_mm
import relief_trace as rt
from rear_signature import engrave
P=json.loads((Path(__file__).parent/'parameters.json').read_text())
W,L,H,T,F,R,e=(float(P[k]) for k in ('width','depth','height','wall','floor','corner','relief'))
NX,ND=(float(P[k]) for k in ('mouth_width','mouth_depth'))
lo,hi,y0=-W/2+e,W/2-e,e
X=hi-lo
assert min(X,L)>2*R+6 and T>0 and R>T and X>NX+12 and H>ND+15 and F>1
def checked(q,n=1):
 assert q.isValid() and len(q.Solids)==n,(q.isValid(),len(q.Solids))
 return q
def fuse(q, parts):
 return checked(q.fuse(parts).removeSplitter()) if parts else q
def roundbox(x,y,z,w,l,h,r):
 q=Part.makeBox(w,l,h,V(x,y,z))
 return q.makeFillet(r,[j for j in q.Edges if j.BoundBox.ZLength>h*.99])
def line(a,b): return Part.makeLine(a,b)
def bez(points):
 c=Part.BezierCurve();c.setPoles(points);return c.toShape()
def mouth(p):
 # Two cubic shoulders, flat / tangent ends. p(x,z) specifies the plane.
 a=NX/2; b=a*.46
 return [bez([p(-a,H),p(-a*.70,H),p(-b*.95,H-ND),p(0,H-ND)]),
         bez([p(0,H-ND),p(b*.95,H-ND),p(a*.70,H),p(a,H)])]
def frontpoint(x,z):return V(x,y0+.04,z)
def opening():
 p=lambda x,z:V(x,-1,z)
 seg=mouth(p);a=NX/2
 return Part.Face(Part.Wire(seg+[line(p(a,H),p(a,H+1)),
 line(p(a,H+1),p(-a,H+1)),line(p(-a,H+1),p(-a,H))])).extrude(V(0,y0+T+2,0))
def common():
 out=roundbox(lo,y0,0,X,L-y0,H,R)
 inn=roundbox(lo+T,y0+T,F,X-2*T,L-y0-2*T,H+1-F,R-T)
 raw=checked(out.cut(inn).cut(opening()).removeSplitter())
 return raw
def plane(which):
 if which=='front':return frontpoint,V(0,-1,0)
 x=hi-.04 if which=='right' else lo+.04
 return lambda u,z:V(x,u,z),V(1 if which=='right' else -1,0,0)
def shape(points,which='front',height=e):
 p,d=plane(which)
 start=cur=p(*points[0]);edges=[]
 for item in points[1:]:
  if len(item)==2:
   end=p(*item);edges.append(line(cur,end))
  else:
   end=p(*item[-2:]);edges.append(bez([cur,p(*item[:2]),p(*item[2:4]),end]))
  cur=end
 if (start-cur).Length>1e-8:edges.append(line(cur,start))
 return Part.Face(Part.Wire(edges)).extrude(d*(height+.04))
def disk(u,z,r,which,height=e):
 p,d=plane(which)
 return Part.makeCylinder(r,height+.04,p(u,z),d)
def stroke(coords, width, where='front', height=e):
 p,d=plane(where); pieces=[]
 for (x,z),(u,v) in zip(coords,coords[1:]):
  length=math.hypot(u-x,v-z)
  if length<1e-9:continue
  a,b=-(v-z)*width/(2*length),(u-x)*width/(2*length)
  pieces.append(shape([(x+a,z+b),(u+a,v+b),(u-a,v-b),(x-a,z-b)],where,height))
 return pieces+[disk(x,z,width/2,where,height) for x,z in dict.fromkeys(coords)]
def transform(points, fx, fz):
 q=[]
 for item in points:
  vals=[]
  for x,z in zip(item[::2],item[1::2]):vals += [fx(x),fz(z)]
  q.append(tuple(vals))
 return q
def border_front():
 # Closed inner line, following the notch as an exact translated Bézier pair.
 r=2.2; x=hi-R-0.2; z=2.5; shift=float(P['frame_inset']); k=float(P['frame_line'])
 # Construct an exact curved annulus by subtracting the inset panel.
 def panel(ix):
  side=x-ix; bottom=z+ix; top=H-shift-ix;a=NX/2
  p=lambda x,z:frontpoint(x,z)
  def arc(s,m,t):return Part.Arc(p(*s),p(*m),p(*t)).toShape()
  g=.29289322*r
  s=[line(p(-side+r,bottom),p(side-r,bottom)),
     arc((side-r,bottom),(side-g,bottom+g),(side,bottom+r)),
     line(p(side,bottom+r),p(side,top-r)),arc((side,top-r),(side-g,top-g),(side-r,top)),
     line(p(side-r,top),p(a,top))]
  seg=mouth(lambda u,v:p(u,v-shift-ix))
  s+=list(reversed([j.reversed() for j in seg]))
  s+=[line(p(-a,top),p(-side+r,top)),arc((-side+r,top),(-side+g,top-g),(-side,top-r)),
      line(p(-side,top-r),p(-side,bottom+r)),
      arc((-side,bottom+r),(-side+g,bottom+g),(-side+r,bottom))]
  return Part.Face(Part.Wire(s)).extrude(V(0,-(e+.04),0))
 return checked(panel(0).cut(panel(k)))
def front_map(x,z):
 return (x/740-.5)*(X-2*R-.9), 2.5+(1-z/480)*(H-5.3)

def side_map(x,z):
 begin=y0+R+.85; end=L-R-.85
 return begin+x/1000*(end-begin), 2.2+(1-z/290)*(H-4.4)

def path_map(points,map2):
 out=[]
 for entry in points:
  pt=[]
  for i in range(0,len(entry),2): pt.extend(map2(*entry[i:i+2]))
  out.append(tuple(pt))
 return out

def rel(points, map2, where, height):
 return shape(path_map(points,map2),where,height)

def ridge(points, map2, where, width, height):
 coords=[map2(*pt) for pt in points]; origin,n=plane(where)
 wire=Part.makePolygon([origin(*pt) for pt in coords])
 try:
  if wire.isClosed():
   ring=Part.Face(wire.makeOffset2D(width/2)).cut(Part.Face(wire.makeOffset2D(-width/2)))
   if ring.isNull() or ring.Area<wire.Length*width*.82:raise ValueError("collapsed offset")
  else:
   ring=wire.makeOffset2D(width/2,0,True,False)
  solid=ring.extrude(n*(height+.04))
  if solid.isValid() and len(solid.Solids)==1:return [solid]
 except Exception:
  pass
 # Some tightly self-approaching paths cannot be offset by OCC in one go.
 fragments=stroke(coords,width,where,height)
 return [checked(fragments[0].fuse(fragments[1:]).removeSplitter())]

def loft_profile(points,map2,where,levels):
 """Coaxial, interpolable B-rep sections with printable side ramps."""
 origin,d=plane(where)
 wires=[]
 for offset,sx,sz in levels:
  def point(x,z):
   u,v=map2(x,z)
   return origin(u*sx[0]+sx[1],v*sz[0]+sz[1])+d*offset
  pos=point(*points[0]); first=pos; edges=[]
  for item in points[1:]:
   end=point(*item[-2:])
   if len(item)==2:
    if (end-pos).Length>1e-8:edges.append(line(pos,end))
   else:edges.append(bez([pos,point(*item[:2]),point(*item[2:4]),end]))
   pos=end
  if (first-pos).Length>1e-8:edges.append(line(pos,first))
  wires.append(Part.Wire(edges))
 return checked(Part.makeLoft(wires,True,True,False))

def modeled(points,map2,where,height,center,scale=.94):
 # Ruled shoulder and top cap retain the explicitly traced silhouette; the
 # top section contracts about the local relief center, not the box center.
 cx,cz=map2(*center)
 return loft_profile(points,map2,where,[(0,(1,0),(1,0)),
  (.04+height*.37,(1,0),(1,0)),(.04+height,(scale,cx*(1-scale)),(scale,cz*(1-scale)))])

def bird_swell(points,map2,where,height,center):
 cx,cz=map2(*center)
 levels=[(.0,1),(.32,.99),(.63,.91),(.85,.76),(1,.58)]
 return loft_profile(points,map2,where,[(0 if not h else .04+h*height,
     (scale,cx*(1-scale)),(scale,cz*(1-scale))) for h,scale in levels])

def b_pair(where,mapping, is_front=False):
 out=[]
 for mirror in (False,True):
  def f(x,z):return mapping(740-x if mirror else x,z)
  for pts in rt.B_FIELD:
   out+=ridge(pts,f,where,.57 if is_front else .62,e*.32)
  out.extend([modeled(rt.B_BODY,f,where,e*.82,(160,334),.94),
              modeled(rt.B_HEAD,f,where,e*.94,(162,171),.94)])
  out+=ridge([(110,154),(185,153),(216,155)],f,where,.82,e)
  out.append(rel(rt.B_CROWN,f,where,e))
  loc=f(237,178)
  out.append(disk(*loc,.98 if is_front else .90,where,e))
  out+=ridge([(266,213),(282,214),(292,213)],f,where,.65,e)
  out+=ridge([(176,221),(162,225),(172,231),(195,228)],f,where,.9,e*.72)
  out+=ridge([(258,245),(256,289),(248,306),(74,305),(58,327),(54,413),(67,425),(129,424),(128,390)],f,where,.69,e*.98)
 return out

def b_pair_cuts(where,mapping):
 cuts=[]; _,normal=plane(where)
 for mirror in (False,True):
  f=lambda x,z:mapping(740-x if mirror else x,z)
  for profile,depth in ((rt.B_HEAD_CHANNEL,.46),(rt.B_MOUTH,.52)):
   pocket=rel(profile,f,where,e)
   pocket.translate(normal*depth)
   # Do not erase the separate curls, eyebrow, or eyeball.
   shields=[rel(rt.B_CROWN,f,where,2*e),disk(*f(237,178),1.06,where,2*e)]
   if profile is rt.B_HEAD_CHANNEL:
    shields+=ridge([(110,154),(185,153),(216,155)],f,where,.85,2*e)
    pocket=pocket.cut(Part.makeCompound(shields))
   cuts.append(pocket)
  for belly in ridge(rt.B_BELLY_CHANNEL,f,where,.95,e):
   belly.translate(normal*.48)
   cuts.append(belly)
 return cuts

def b_front():
 out=[border_front()]
 out+=b_pair('front',front_map,True)
 out+=ridge([(370,133),(370,467)],front_map,'front',1.25,e*.82)
 cuts=b_pair_cuts('front',front_map)
 for which in ('left','right'):
  for start,end in ((9,500),(513,991)):
   def f(x,z):return side_map(start+x/740*(end-start),6+z/480*274)
   cuts+=b_pair_cuts(which,f)
 return out,Part.makeCompound(cuts)

def d_front():
 # Foreground and bird's visible subdivisions are each traced from the
 # approved original, with no grayscale-to-height conversion.
 q=[border_front(),modeled(rt.D_BRANCH,front_map,'front',e*.63,(368,332),.972),
    modeled(rt.D_TAIL,front_map,'front',e*.60,(568,396),.91),
    bird_swell(rt.D_BIRD,front_map,'front',e*.93,(377,217)),
    modeled(rt.D_WING,front_map,'front',e,(442,276),.935),
    modeled(rt.D_BEAK,front_map,'front',e*.92,(262,165),.92)]
 q+=ridge([(486,347),(526,376),(555,407),(589,440),(632,453)],front_map,'front',.73,e*.72)
 for path in [[(377,350),(361,370),(343,382),(331,395),(326,416)],
              [(411,351),(398,379),(381,393),(371,424)],
              [(352,385),(339,406),(337,421)],[(391,390),(381,405),(381,424)],
              [(402,393),(391,408),(391,423)]]:
  q+=ridge(path,front_map,'front',.76,e*.79)
 p=front_map(308,164)
 q.append(disk(*p,1.05,'front',e))
 cut=disk(*p,.47,'front',e)
 # A shallow inset eye, terminating outside the wall, leaves a continuous solid.
 cut.translate(V(0,-.66,0))
 feathers=[]
 for profile in (rt.D_FEATHER1,rt.D_FEATHER2):
  groove=rel(profile,front_map,'front',e)
  groove.translate(V(0,-.58,0))
  feathers.append(groove)
 return q,Part.makeCompound([cut,*feathers])

def rect_border(map2,where,x0,z0,x1,z1,width,depth):
 return ridge([(x0,z0),(x1,z0),(x1,z1),(x0,z1),(x0,z0)],map2,where,width,depth)

def d_sides(where):
 out=rect_border(side_map,where,3,3,997,285,1.04,e*.57)
 # Measure two wheel centers and spoke phases from the rectified side.
 # World-space circular wheels correct residual perspective in the concept.
 for cx,cz,rx,phase in [(363,152,125,-1.57),(799,147,122,-1.60)]:
  u,z=side_map(cx,cz)
  radius=min((side_map(cx+rx,cz)[0]-u),z-3.7,H-z-3.7)
  outer=disk(u,z,radius,where,e)
  ring=outer.cut(disk(u,z,radius-1.82,where,e))
  out+=[ring,disk(u,z,radius*.215,where,e)]
  for j in range(5):
   angle=phase+2*math.pi*j/5
   a,b=math.cos(angle),-math.sin(angle); inner=radius*.065; tip=radius-.62
   verts=[(u+a*r-b*w,z+b*r+a*w) for r,w in [(inner,-2.25),(tip,-1.6),(tip,1.6),(inner,2.25)]]
   out.append(shape(verts,where,e*.75))
 for pts in rt.D_SIDE_KEYS:out+=ridge(pts,side_map,where,1.48,e*.78)
 return out

def b_side(where):
 out=rect_border(side_map,where,4,4,996,284,1.0,e*.68)
 for a,b in ((9,500),(513,991)):
  def p(x,z): return side_map(a+x/740*(b-a),6+z/480*274)
  out+=b_pair(where,p)
  out+=ridge([(370,2),(370,477)],p,where,.92,e*.75)
 out+=ridge([(507,5),(507,285)],side_map,where,1.3,e*.71)
 return out

def make_divider(raw):
 inner=X-2*T;gap=float(P['divider_clearance_x_total']); plate=float(P['divider_thick'])
 slot=plate+float(P['divider_slot_clearance_total']); rail=1.45; post=1.65
 ys=[y0+T+(L-y0-2*T)*f for f in P['divider_positions_fraction']]
 assert all(b-a>slot+2*post for a,b in zip(ys,ys[1:])) and inner>12
 z=F; p=H*.43; divH=H*.67
 # Flat-bottom divider with rounded top corners in the XZ plane.
 q=Part.makeBox(inner-gap,plate,divH,V(-(inner-gap)/2,-plate/2,z))
 top=[j for j in q.Edges if j.BoundBox.YLength>plate*.99 and j.BoundBox.ZMin>z+divH-.01]
 q=checked(q.makeFillet(4,top))
 ribs=[Part.makeBox(rail+.06,post,p,V(x,at,z-.025))
       for x in (-inner/2-.03,inner/2-rail-.03)
       for y in ys for at in (y-slot/2-post,y+slot/2)]
 body=fuse(raw,ribs)
 # Vertical insertion at all indexed locations. Divider only rests on the floor.
 for y in ys:
  for dz in (0,4,10,25,44):
   v=q.copy();v.translate(V(0,y,dz))
   assert body.common(v).Volume<1e-7,(y,dz)
 return body,q,ys,slot,inner
def save(name,q):
 p=ROOT/'STEP'/name
 q.exportStep(str(p));ensure_mm(p,q);s=checked(Part.read(str(p)),len(q.Solids))
 delta=abs(s.Volume-q.Volume)
 print(name, 'roundtrip volume delta mm3', round(delta,6), flush=True)
 assert delta/max(q.Volume,1)<.0005,(s.Volume,q.Volume)
 bb=s.optimalBoundingBox(False,False)
 return dict(file=name,sha256=hashlib.sha256(p.read_bytes()).hexdigest(),solid_count=len(s.Solids),
   volume_mm3=round(s.Volume,3),bounds=[round(getattr(bb,k),5) for k in ('XLength','YLength','ZLength')],face_count=len(s.Faces))
def main():
 body,div,ys,slot,inner=make_divider(common())
 body,mark=engrave(body,L,T)
 stats={}
 for variant in ('B','D'):
  extras,cut=b_front() if variant=='B' else d_front()
  for where in ('left','right'): extras+=(b_side(where) if variant=='B' else d_sides(where))
  print(variant,'fusing',len(extras),'ornaments',flush=True)
  final=fuse(body,extras)
  if cut:
   # Fine incised eye does not penetrate the original wall.
   final=checked(final.cut(cut).removeSplitter())
  assert final.common(Part.makeBox(X-2*T-4,L-2*T-y0-4,H-F+1,
        V(-X/2+T+2,y0+T+2,F+.0001))).Volume<1e-5
  stats[variant]=save(variant+'_Snack_Bin.step',final)
  stats.setdefault('rear_signature',{})[variant]=mark
  seated=div.copy();seated.translate(V(0,round(ys[2],3),0))
  assert final.common(seated).Volume<1e-7
  stats[variant+'set']=save(variant+'_Assembly_REFERENCE.step',Part.makeCompound([final,seated]))
 stats['divider']=save('Shared_Divider.step',div)
 stats['slot']={'centers_y_mm':[round(v,3) for v in ys],'actual_width_y':round(slot,3),'total_clearance_y':round(slot-P['divider_thick'],3),'body_inner_nominal_width_x':round(inner,3),'total_clearance_x':P['divider_clearance_x_total'],'insert_pose_intersections_mm3':0,'pose_count_per_slot':5}
 (ROOT/'QA'/'geometry.json').write_text(json.dumps(stats,ensure_ascii=False,indent=2)+'\n')
 print(json.dumps(stats,ensure_ascii=False))
if __name__=='__main__':main()
