#!/usr/bin/env python3
"""Render measurement.json as a reviewable PNG. python3 render.py measurement.json output.png"""
import json,sys,statistics
from PIL import Image,ImageDraw,ImageFont
D=json.load(open(sys.argv[1])); im=Image.new('RGB',(1600,1120),'#f7f8fb');d=ImageDraw.Draw(im)
def font(n):return ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf',n)
def text(x,y,s,n=22,c='#182134'):d.text((x,y),s,font=font(n),fill=c)
text(50,30,'GitLab MR watch: real-server measurement',38)
text(50,87,'Linux | same machine | fresh databases | live GitLab.com | Replay agent | timers unchanged',21)
text(50,126,'Unchanged pending CI: repeated two-minute sweeps (warm-up excluded)',25)
for side,x,color,sha,label in [('base',50,'#ba4539','3a5d7f39a8','BEFORE'),('head',825,'#187e70','87b6fa53fc','AFTER')]:
 rows=[r for r in D[side]['sweeps'] if 2<r['elapsedMinutes']<20 and r['glabCalls']]
 counts=[r['glabCalls'] for r in rows];times=[r['durationMs']/1000 for r in rows]
 d.rounded_rectangle((x,180,x+725,1005),radius=15,fill='white',outline='#d8deea',width=2)
 text(x+25,198,label+'  '+sha,27,color)
 if not rows:continue
 text(x+25,245,f'{statistics.median(counts):g} glab calls / sweep',34,color)
 text(x+25,292,f'n={len(rows)}; range {min(counts)}–{max(counts)} calls',23)
 text(x+25,330,f'Median sweep: {statistics.median(times):.3f} s',26)
 text(x+25,369,f'Range: {min(times):.3f}–{max(times):.3f} s',21)
 text(x+25,415,'Elapsed     Calls   Sweep seconds',21)
 for i,r in enumerate(rows):
  y=455+i*47
  text(x+25,y,f'{r["elapsedMinutes"]:5.2f} min',20)
  d.rectangle((x+185,y+5,x+185+r['glabCalls']*20,y+23),fill=color)
  text(x+435,y,str(r['glabCalls']),20)
  text(x+525,y,f'{r["durationMs"]/1000:.3f}',20)
 text(x+25,920,'Calls attributed by trace ancestry to',20)
 text(x+25,951,'PullRequestWatchReactor.sweep only.',20)
text(50,1030,'Network duration is secondary; request count is the primary performance measure.',22)
text(50,1070,'Includes all glab reads in each watch sweep; excludes the separate link-sync reactor.',21)
im.save(sys.argv[2])
for side,label,sha,color in [('base','BEFORE','3a5d7f39a8','#ba4539'),('head','AFTER','87b6fa53fc','#187e70')]:
 rows=[r for r in D[side]['sweeps'] if 2<r['elapsedMinutes']<20 and r['glabCalls']]
 batches=[rows[i:i+3] for i in range(0,len(rows),3)]
 calls=[sum(r['glabCalls'] for r in b) for b in batches]
 times=[sum(r['durationMs'] for r in b)/1000 for b in batches]
 panel=Image.new('RGB',(1050,1170),'#f7f8fb');d=ImageDraw.Draw(panel)
 text(45,30,label+' — GitLab MR watch',34,color)
 text(45,80,sha+' | Linux | real development server',23)
 text(45,120,'Live GitLab.com, fresh database, Replay multi-turn',22)
 text(45,157,'Unmodified two-minute polling; unchanged running CI',22)
 text(45,218,'Three consecutive batches, three sweeps each',27)
 text(45,265,'Batch     glab calls     Total sweep time',23)
 for i,(c,t) in enumerate(zip(calls,times)):
  text(45,310+i*48,f'{i+1}                 {c:2d}                     {t:.3f} s',25,color)
 text(45,480,f'Median: {statistics.median(calls):g} calls / {statistics.median(times):.3f} s',30,color)
 text(45,525,f'Batch spread: {max(calls)-min(calls)} calls / {max(times)-min(times):.3f} s',22)
 text(45,590,'All nine individual sweeps (warm-up excluded)',25)
 text(45,635,'Elapsed min       glab calls       Sweep seconds',22)
 for i,r in enumerate(rows):
  text(45,680+i*37,f'{r["elapsedMinutes"]:6.3f}                    {r["glabCalls"]:2d}                       {r["durationMs"]/1000:.3f}',22)
 text(45,1040,'Attributed by trace ancestry to PullRequestWatchReactor.',20)
 text(45,1075,'Separate link-sync calls are excluded. Same MR and machine.',20)
 text(45,1110,'Each batch is part of one continuous live watch.',20)
 panel.save(str(__import__('pathlib').Path(sys.argv[2]).with_name(side+'-measurement.png')))

