"""Check the shared functional volume and source identity after a relief revision."""
import hashlib,json,sys
from pathlib import Path
import build as b
from rear_signature import make_mark
sha=lambda p: hashlib.sha256(Path(p).read_bytes()).hexdigest()
root=b.ROOT
qa=root/'QA'/'geometry.json'
audit=json.loads(qa.read_text())
raw,expected,ys,slot,unused=b.make_divider(b.common())
p=root/'STEP'/audit['divider']['file']
assert sha(p)==audit['divider']['sha256']
div=b.Part.read(str(p));assert div.isValid() and len(div.Solids)==1
assert abs(div.Volume-expected.Volume)<1e-4
report={}
for k in ('B','D'):
 inp=root/'STEP'/audit[k]['file']
 assert sha(inp)==audit[k]['sha256']
 q=b.Part.read(str(inp));assert q.isValid() and len(q.Solids)==1
 # Ignore only the intended shallow rear inscription.
 expected_core=raw.cut(make_mark(b.L)) if k in audit.get("rear_signature",{}) else raw
 missing=expected_core.cut(q).Volume
 assert missing<.0001,(k,missing)
 worst=0.0
 for y in ys:
  for dz in (0,4,10,25,44):
   p=div.copy();p.translate(b.V(0,y,dz))
   worst=max(worst,q.common(p).Volume)
 assert worst<.0001,(k,worst)
 report[k]={'functional_body_missing_mm3':round(missing,8),'worst_insertion_intersection_mm3':round(worst,8),'pose_count':25,'body_sha256':sha(inp)}
 print(k,report[k],flush=True)
(root/'QA'/'relief-fit.json').write_text(json.dumps(report,indent=2)+'\n')
