"""Reproduce the exact reviewed browser module from supplied editable source/data."""
from pathlib import Path
import hashlib,json
D=Path(__file__).resolve().parent
def render():
 p=json.loads((D/'provenance.json').read_text());tables={}
 for c in p['tables']:
  f=D/c['json'];assert hashlib.sha256(f.read_bytes()).hexdigest()==c['sha256']
  rows=json.loads(f.read_text())['rows'];start=60 if c['package']=='anthroplus' else 0;per=[]
  for sex in [1,2]:
   rr=sorted([r for r in rows if r['sex']==sex],key=lambda r:r['age'])
   assert [r['age'] for r in rr]==list(range(start,start+len(rr)))
   per.append([[r[k] for k in ['l','m','s']] for r in rr])
  tables[c['object']]=per
 # Retain the original scientific generation order, which controls literal byte order.
 order=['growthstandards_lenanthro','growthstandards_bmianthro','hfa_growth_standards','bfa_growth_standards','growthstandards_weianthro','wfa_growth_standards']
 t=(D/'model-template.mjs.txt').read_text();assert t.count('__TABLES__')==1
 out=t.replace('__TABLES__',json.dumps({k:tables[k] for k in order},separators=(',',':'))).encode()
 assert hashlib.sha256(out).hexdigest()==p['scientificModuleSHA256']
 return out
if __name__=='__main__':
 out=render()
 (D/'calculate.mjs').write_bytes(out)
 print(json.dumps({'moduleSHA256':hashlib.sha256(out).hexdigest()}))
