#!/usr/bin/env python3
"""Build public A/B captures from measurement.json and projection-measurement.json.
Usage: python3 report.py BASE_RUN HEAD_RUN OUTPUT_DIRECTORY
"""
import json,pathlib,sys,statistics,html,sqlite3,hashlib
out=pathlib.Path(sys.argv[3]);out.mkdir(parents=True,exist_ok=True)
reports=[]
for arg in sys.argv[1:3]:
 root=pathlib.Path(arg);raw=json.loads((root/'measurement.json').read_text());derived=json.loads((root/'projection-measurement.json').read_text())
 public={'side':raw['side'],'commit':raw['commit'],'environment':raw['environment'],'checkpoints':[]}
 for c,r in zip(derived['checkpoints'],raw['checkpoints']):
  keys={(x['name'],x['durationMs']):x['startTimeUnixNano'] for x in r['spans']}
  records=sorted(c['records'],key=lambda x:int(keys[(x['name'],x['durationMs'])]))
  for record in records:record['startTimeUnixNano']=keys[(record['name'],record['durationMs'])]
  boundaries=[int(x['startTimeUnixNano']) for x in records if x['name']=='Orchestrator.dispatchMessage'][::19]
  def blocks(name,key):
   selected=[x for x in records if x['name']==name and (name!='Orchestrator.startNextQueuedRun' or x['writesEvents'])]
   groups=[[x[key] for x in selected if int(x['startTimeUnixNano'])>=start and (i==2 or int(x['startTimeUnixNano'])<boundaries[i+1])] for i,start in enumerate(boundaries)]
   assert len(groups)==3 and all(groups),(name,[len(g) for g in groups])
   medians=[statistics.median(g) for g in groups];values=[x[key] for x in selected]
   return {'n':len(values),'medianMs':statistics.median(values),'minMs':min(values),'maxMs':max(values),'blockSampleCounts':[len(g) for g in groups],'blockMediansMs':medians,'medianOfBlockMediansMs':statistics.median(medians),'spreadBetweenBlockMediansMs':max(medians)-min(medians),'samplesMs':values}
  public['checkpoints'].append({'seedRuns':c['seedRuns'],'before':c['before'],'after':c['after'],'deliveries':r['idleAndBurstDeliveries'],'dispatch':blocks('Orchestrator.dispatchMessage','durationMs'),'dispatchProjectionReads':blocks('Orchestrator.dispatchMessage','projectionReadMs'),'queuedStartsDoingWork':blocks('Orchestrator.startNextQueuedRun','durationMs'),'queuedStartProjectionReads':blocks('Orchestrator.startNextQueuedRun','projectionReadMs'),'sanitizedCommandSpans':records})
 with sqlite3.connect(f'file:{root}/home/userdata/statev2.sqlite?mode=ro',uri=True) as db:
  messages=db.execute("select role,json_extract(payload_json,'$.text') from orchestration_v2_projection_messages where role in ('user','assistant') order by role,json_extract(payload_json,'$.text')").fetchall()
 public['behaviorFingerprint']={'messageCount':len(messages),'sortedRoleAndTextSha256':hashlib.sha256(json.dumps(messages,separators=(',',':')).encode()).hexdigest()}
 public['final']=raw['final'];reports.append(public);(out/(public['side']+'.json')).write_text(json.dumps(public,indent=2))
 lines=['REAL SERVER COMMAND PROJECTION MEASUREMENT',f'Commit: {public["commit"]}','Environment: Linux x86_64; Node '+public['environment']['node'],'Fresh server-created state; synthetic git project; repository Replay (dev), multi-turn.','Three repeated blocks per checkpoint: seven idle sends followed by three four-send concurrent bursts.','Times below are server spans, excluding CLI/process startup. Each block has 19 dispatches; actual queued-start sample counts are recorded in the JSON.','Queued starts are identified by descendant EventSink.write spans; early guards are excluded.','Projection reads are summed readCanonicalProjection descendants within each command.','']
 for c in public['checkpoints']:
  lines.append(f'Checkpoint: {c["seedRuns"]} prior runs; after measurement: {c["after"]["runs"]} completed runs')
  for key in ['dispatch','dispatchProjectionReads','queuedStartsDoingWork','queuedStartProjectionReads']:
   s=c[key];lines.append(f'{key}: n={s["n"]}, median={s["medianMs"]:.3f} ms, range={s["minMs"]:.3f}..{s["maxMs"]:.3f}; block medians='+', '.join(f'{m:.3f}' for m in s['blockMediansMs'])+f' ms; block spread={s["spreadBetweenBlockMediansMs"]:.3f} ms')
  lines.extend([f'Behavior: {c["after"]["completedRuns"]} completed / {c["after"]["runs"]} total; user messages={c["after"]["userMessages"]}; assistant replies={c["after"]["assistantMessages"]}; compactions={c["after"]["compactions"]}.',''])
 (out/(public['side']+'.txt')).write_text('\n'.join(lines))
a,b=reports
assert a['final']==b['final'], 'Final counts or replay replies differ'
assert a['behaviorFingerprint']==b['behaviorFingerprint'], 'Message texts differ'
comparison=[]
for x,y in zip(a['checkpoints'],b['checkpoints']):
 row={'seedRuns':x['seedRuns']}
 for k in ['dispatch','dispatchProjectionReads','queuedStartsDoingWork','queuedStartProjectionReads']:
  baseline=x[k]['medianOfBlockMediansMs'];head=y[k]['medianOfBlockMediansMs'];spread=max(x[k]['spreadBetweenBlockMediansMs'],y[k]['spreadBetweenBlockMediansMs'])
  row[k]={'baseMedianMs':baseline,'headMedianMs':head,'speedup':baseline/head,'medianDifferenceMs':baseline-head,'maximumBlockSpreadMs':spread,'betterThanSpread':baseline-head>spread}
 comparison.append(row)
(out/'comparison.json').write_text(json.dumps(comparison,indent=2));print(json.dumps(comparison,indent=2))
# Standalone chart: static SVG converted to PNG by the capture command.
W,H=1200,690;left,top,cw,ch=95,110,475,420
parts=[f'<svg xmlns="http://www.w3.org/2000/svg" width="{W}" height="{H}" viewBox="0 0 {W} {H}"><rect width="1200" height="690" fill="#101722"/>','<g font-family="DejaVu Sans" fill="#e8edf6"><text x="60" y="48" font-size="26">Command reads without compaction: real server A/B</text><text x="60" y="78" font-size="15" fill="#adbcd1">Linux x86_64 · Replay multi-turn · fresh synthetic state · median of three block medians</text>']
for panel,key,title in [(0,'dispatch','Message dispatch'),(1,'queuedStartsDoingWork','Queued start (did work)')]:
 x0=left+panel*560; maximum=max(c[key]['medianOfBlockMediansMs'] for p in reports for c in p['checkpoints'])*1.18
 parts.append(f'<text x="{x0}" y="{top+20}" font-size="21">{title}</text>')
 for j in range(5):
  y=top+ch-j*ch/4;v=j*maximum/4;parts.append(f'<path d="M{x0},{y}h{cw}" stroke="#2c3a4b"/><text x="{x0-12}" y="{y+5}" text-anchor="end" font-size="12">{v:.0f}</text>')
 for p,color in zip(reports,['#ffac78','#71dfc3']):
  points=[]
  for i,c in enumerate(p['checkpoints']):
   x=x0+35+i*(cw-70)/2;s=c[key];y=top+ch-s['medianOfBlockMediansMs']/maximum*ch;points.append(f'{x},{y}')
   label_x=x+(45 if p['side']=='after' and i==0 else 0);label_y=y+(20 if p['side']=='after' and i==0 else -13)
   parts.extend([f'<circle cx="{x}" cy="{y}" r="5" fill="{color}"/>',f'<text x="{label_x}" y="{label_y}" text-anchor="middle" font-size="14" fill="{color}">{s["medianOfBlockMediansMs"]:.1f} ms</text>'])
  parts.append(f'<polyline points="{" ".join(points)}" fill="none" stroke="{color}" stroke-width="3"/>')
 for i,c in enumerate(a['checkpoints']):parts.append(f'<text x="{x0+35+i*(cw-70)/2}" y="{top+ch+27}" text-anchor="middle" font-size="14">{c["seedRuns"]:,}</text>')
 parts.append(f'<text x="{x0+cw/2}" y="{top+ch+57}" text-anchor="middle" font-size="14">Completed runs before measurement</text>')
parts.extend([f'<text x="80" y="625" fill="#ffac78" font-size="17">Before: {a["commit"][:10]}</text>',f'<text x="390" y="625" fill="#71dfc3" font-size="17">After: {b["commit"][:10]}</text>','<text x="80" y="657" font-size="14" fill="#adbcd1">All sends completed with one assistant reply each. Zero compaction items on both commits.</text></g></svg>'])
(out/'comparison.svg').write_text(''.join(parts))
