"""Render the engraved rear surface from STEP, not from the logo image."""
from pathlib import Path
import json
import numpy as np
from PIL import Image
from scipy.ndimage import gaussian_filter
from relief_compare import read_step,draw_height
root=Path(__file__).resolve().parent.parent
# read_step's tessellated coordinates are transformed to rear reading direction.
spec=dict(axes=(0,2,1),sign=1,u=(-24,24),v=(5,31),size=(960,520))
for k in ('B','D'):
 path=root/'STEP'/f'{k}_Snack_Bin.step'
 xyz,tri=read_step(path);xyz[:,0]*=-1
 h=draw_height((xyz,tri),spec)
 wall=json.loads((root/'Source/parameters.json').read_text())['depth']
 assert np.isfinite(h).all() and abs(h.max()-wall)<.002
 assert abs(h.min()-(wall-.25))<.002,(k,h.min())
 height=gaussian_filter(h,.8)
 dy,dx=np.gradient(height,.05,.05)
 lighting=np.clip((.81+.33*dx+.50*dy)/np.sqrt(1+dx*dx+dy*dy),.1,1)
 base=np.array((133,149,112) if k=='D' else (109,131,88))
 level=np.clip(.30+.81*lighting-.65*(wall-height),0,1.2)
 pix=np.clip(level[:,:,None]*base,0,255).astype('uint8')
 Image.fromarray(pix).save(root/'QA'/f'{k}-rear-signature.png',optimize=True)
