"""Sign existing latest STEP without regenerating approved front/side ornaments."""
import json,sys
from pathlib import Path
import build as b
from rear_signature import engrave,make_mark
root=b.ROOT; qa=root/'QA'/'geometry.json'
a=json.loads(qa.read_text()); report={}
source=Path(sys.argv[1])
def checked_item(path,item):
 import hashlib
 assert hashlib.sha256(path.read_bytes()).hexdigest()==item['sha256'],path
 return b.Part.read(str(path))
div=checked_item(source/a['divider']['file'],a['divider'])
for k in ('B','D'):
 item=a[k];body=checked_item(source/item['file'],item)
 new,stats=engrave(body,b.L,b.T)
 a[k]=b.save(item['file'],new)
 assert a[k]['bounds']==item['bounds']
 # Re-check signed output entirely against the exact earlier body minus mark.
 signed=checked_item(root/'STEP'/item['file'],a[k])
 assert abs(signed.Volume-new.Volume)<.002
 plate=div.copy();plate.translate(b.V(0,a['slot']['centers_y_mm'][2],0))
 a[k+'set']=b.save(a[k+'set']['file'],b.Part.makeCompound([signed,plate]))
 stats.update(before_body_sha256=item['sha256'],body_sha256=a[k]['sha256'])
 report[k]=stats
 print(k, stats, flush=True)
a['rear_signature']=report
qa.write_text(json.dumps(a,ensure_ascii=False,indent=2)+'\n')
(root/'QA'/'rear-signature.json').write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n')
