"""Orthographic rasters from STEP geometry, with the same framing and light."""
import argparse
from pathlib import Path
import sys,json,subprocess,os
if len(sys.argv)==3 and sys.argv[1]=='--mesh':
 sys.path.insert(0,"/Applications/FreeCAD.app/Contents/Resources/lib")
 import FreeCAD,Part
 shape=Part.read(sys.argv[2])
 assert shape.isValid()
 verts,tri=shape.tessellate(.045)
 print(json.dumps([[(v.x,v.y,v.z) for v in verts],tri],separators=(',',':')))
 raise SystemExit(0)
import numpy as np
from PIL import Image, ImageDraw
from scipy.ndimage import gaussian_filter
SPECS={
 "front":dict(axes=(0,2,1),sign=-1,u=(-32.75,32.75),v=(2.5,45.2),size=(740,480)),
 "side":dict(axes=(1,2,0),sign=1,u=(6.65,164.15),v=(2.2,45.8),size=(1000,290)),
}
def read_step(path):
 freecad=os.environ.get('FREECAD_PYTHON','/Applications/FreeCAD.app/Contents/Resources/bin/python')
 verts,tri=json.loads(subprocess.check_output([freecad,__file__,'--mesh',str(path)]))
 return np.array(verts,dtype=np.float64),tri
def draw_height(mesh, spec):
 pts,tri=mesh
 u,v,d=pts[:,list(spec['axes'])].T
 w,h=spec['size'];u0,u1=spec['u'];v0,v1=spec['v']
 X=(u-u0)*(w-1)/(u1-u0);Y=(v1-v)*(h-1)/(v1-v0)
 Z=d*spec['sign']
 out=np.full((h,w),-np.inf)
 for i,j,k in tri:
  x0,x1,x2=X[[i,j,k]];y0,y1,y2=Y[[i,j,k]]
  ix=max(0,int(np.ceil(min(x0,x1,x2))));ex=min(w-1,int(np.floor(max(x0,x1,x2))))
  iy=max(0,int(np.ceil(min(y0,y1,y2))));ey=min(h-1,int(np.floor(max(y0,y1,y2))))
  if ix>ex or iy>ey:continue
  det=(x1-x0)*(y2-y0)-(y1-y0)*(x2-x0)
  if abs(det)<1e-9:continue
  dy,dx=np.ogrid[iy:ey+1,ix:ex+1];dx=dx-x0;dy=dy-y0
  b=(dx*(y2-y0)-dy*(x2-x0))/det;c=((x1-x0)*dy-(y1-y0)*dx)/det
  ok=(b>=-1e-7)&(c>=-1e-7)&(b+c<=1+1e-7)
  depth=(1-b-c)*Z[i]+b*Z[j]+c*Z[k]
  np.maximum(out[iy:ey+1,ix:ex+1],np.where(ok,depth,-np.inf),out=out[iy:ey+1,ix:ex+1])
 return out
def shade(height,spec):
 w,h=spec['size'];u0,u1=spec['u'];v0,v1=spec['v']
 valid=np.isfinite(height)
 # Keep plain substrate constant and exclude handling/notch interior from lighting.
 flat=-.8 if spec['sign']<0 else 37.2
 present=valid & (height>=flat-.07)
 face_depth=np.where(present,height,flat)
 face_depth=gaussian_filter(face_depth,.78)
 dy,dx=np.gradient(face_depth,(v1-v0)/(h-1),(u1-u0)/(w-1))
 light=(.37*dx+.55*dy+.74)/np.sqrt(1+dx*dx+dy*dy)
 # Directionally stable occlusion at relief feet.
 local=gaussian_filter(face_depth,4)-face_depth
 color=light*.52+.44-np.clip(local*2.2,0,.18)
 rgb=np.clip(color[:,:,None]*np.array([125,136,100])[None,None,:],0,255).astype('uint8')
 rgb[~present]=(216,217,196)
 return Image.fromarray(rgb)
def compare(ref,old,new,dest):
 w,h=ref.size;pad=14; cap=35
 card=Image.new('RGB',(3*w+2*pad,h+cap),(245,243,234));draw=ImageDraw.Draw(card)
 for i,(im,t) in enumerate(zip((ref,old,new),("01  APPROVED IMAGE","02  ORIGINAL CAD","03  REVISED CAD"))):
  x=i*(w+pad); draw.text((x+8,9),t,fill=(39,51,40),font_size=18);card.paste(im,(x,cap))
 card.save(dest,optimize=True)
def main():
 p=argparse.ArgumentParser();p.add_argument('--before',type=Path,required=True);p.add_argument('--after',type=Path,required=True);p.add_argument('--rectified',type=Path,required=True);p.add_argument('--out',type=Path,required=True);a=p.parse_args()
 a.out.mkdir(exist_ok=True,parents=True)
 for variant in ('B','D'):
  old=read_step(a.before/f"{variant}_Snack_Bin.step")
  new=read_step(a.after/f"{variant}_Snack_Bin.step")
  for face,spec in SPECS.items():
   ref=Image.open(a.rectified/f"rect-{variant}-{face}.png").convert('RGB')
   compare(ref,shade(draw_height(old,spec),spec),shade(draw_height(new,spec),spec),a.out/f"{variant}-{face}.png")
   print(variant,face,flush=True)
if __name__=='__main__':main()
