"""Sanitize and summarize drive.py output and the real server trace.
Usage: python3 summarize.py RUN_DIRECTORY SIDE OUTPUT.json
The withReceipt span includes the production receipt/dispatch/event-commit path.
"""
import pathlib,sys,json,statistics,re
run=pathlib.Path(sys.argv[1]);side=sys.argv[2];output=pathlib.Path(sys.argv[3]);data=json.loads((run/f'{side}-results.json').read_text())
groups={}
for line in (run/'home/userdata/logs/server.trace.ndjson').open():
 try:x=json.loads(line)
 except ValueError:continue
 a=x.get('attributes',{});typ=a.get('orchestration_v2.command_type');cmd=a.get('orchestration_v2.command_id','')
 if x.get('name')!='orchestrationV2.dispatch.withReceipt' or typ not in ['secret_request.record','link_request.record']:continue
 m=re.search(r':(?:secret-(?:pending|cancelled):proof-|link-pending:proof-link-)(\d+)-(\d+)-(\d+)$',cmd)
 if not m:continue
 n,batch,i=map(int,m.groups());kind='secret' if typ.startswith('secret') else 'link'
 groups.setdefault((n,kind),[]).append({'batch':batch,'sample':i,'operation':'cancelled' if ':secret-cancelled:' in cmd else 'pending','durationMs':x['durationMs'],'success':x.get('exit',{}).get('_tag')=='Success'})
for p in data['phases']:
 p['dispatchStats']={}
 for kind in ['secret','link']:
  s=groups[p['olderRuns'],kind];v=[x['durationMs'] for x in s];assert len(v)==(30 if kind=='secret' else 15);assert all(x['success'] for x in s)
  p['dispatchStats'][kind]={'span':'orchestrationV2.dispatch.withReceipt','n':len(v),'medianMs':statistics.median(v),'minMs':min(v),'maxMs':max(v),'batchMediansMs':[statistics.median(x['durationMs'] for x in s if x['batch']==b) for b in range(3)],'samples':s}
 cards=p['cards'];expected=15*(data['phases'].index(p)+1)
 assert sum(x['type']=='secret_request' for x in cards)==expected
 assert sum(x['type']=='link_request' for x in cards)==expected
 for c in cards:
  assert c['reason']=='Synthetic performance proof'
  if c['type']=='secret_request':assert c['secretStatus']=='cancelled' and c['status']=='cancelled'
  else:assert c['linkStatus']=='pending' and c['status']=='waiting'
 p['validation']={'secretCards':expected,'linkCards':expected,'allContentsAndAssociationsCorrect':True}
 # Responses and spans are synthetic and retained for independent inspection.
output.write_text(json.dumps(data,indent=2))
for p in data['phases']:
 print(side,p['olderRuns'],p['validation'])
 for k,s in p['dispatchStats'].items():print(f"  {k}: median {s['medianMs']:.3f} ms; range {s['minMs']:.3f}–{s['maxMs']:.3f}; n={s['n']}; batch medians {s['batchMediansMs']}")
