import json,statistics,pathlib,csv
from PIL import Image,ImageDraw,ImageFont
root=pathlib.Path(__file__).parent
rows=json.loads((root/'all-turns.json').read_text())
for r in rows:
 idx=next(i for i,p in enumerate(r['processes']) if p['args']==['config','--get','status.showUntrackedFiles'])
 ps=r['processes'][idx:]
 r['refreshGitMs']=sum(p['durationMs'] for p in ps)
 r['refreshWallMs']=max(p['offsetMs']+p['durationMs'] for p in ps)-ps[0]['offsetMs']
# Strip machine-specific paths, identifiers and timestamps from public output.
for row in rows:
 row['output']={k:v for k,v in row['output'].items() if k in ['status','reply','error']}
 for p in row['processes']:
  p['args']=[a.replace('C:/p/repos/p0','<workspace>').replace('C:\\p\\repos\\p0','<workspace>') for a in p['args']]
(root/'measurements.json').write_text(json.dumps(rows,indent=2))
summary={}
for side in ['base','head']:
 rs=[r for r in rows if r['side']==side]
 summary[side]={'turns':len(rs),'statuses':sorted(set(r['output']['status'] for r in rs)),'replies':sorted(set(r['output']['reply'] for r in rs))}
 for key in ['remoteReadCount','remoteReadMs','gitCount','allGitMs','cliMs','refreshGitMs','refreshWallMs']:
  vals=[r[key] for r in rs]
  summary[side][key]={'median':statistics.median(vals),'min':min(vals),'max':max(vals),'spread':max(vals)-min(vals)}
(root/'summary.json').write_text(json.dumps(summary,indent=2))
print(json.dumps(summary,indent=2))
font='/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf'
f=lambda size:ImageFont.truetype(font,size)
for side,sha,label in [('base','fcf50973f3','Before'),('head','5e924a3545','After')]:
 rs=[r for r in rows if r['side']==side]
 im=Image.new('RGB',(1200,900),'#101820');d=ImageDraw.Draw(im)
 d.text((45,30),f'{label}: real Windows turn-end Git reads',font=f(32),fill='white')
 d.text((45,85),f'Commit {sha} | Windows Server 2025 | Replay command-output',font=f(20),fill='#a9b9ca')
 d.text((45,125),f'{len(rs)} steady turns, two fresh-server batches; same pushed branch, no PR',font=f(20),fill='#a9b9ca')
 vals=summary[side]['remoteReadMs'];ct=summary[side]['remoteReadCount']
 d.text((45,180),f"Remote configuration reads: {ct['median']:g} processes / turn",font=f(27),fill='#6be5bc')
 d.text((45,225),f"Median Git process time: {vals['median']:.1f} ms",font=f(30),fill='white')
 d.text((45,270),f"Range: {vals['min']:.1f}–{vals['max']:.1f} ms (spread {vals['spread']:.1f} ms)",font=f(23),fill='#a9b9ca')
 top,bottom,left,right=360,710,95,1150
 ymax=max(r['remoteReadMs'] for r in rows)*1.15
 for tick in range(0,int(ymax)+1,25):
  y=bottom-tick/ymax*(bottom-top);d.line((left,y,right,y),fill='#34404c');d.text((20,y-12),str(tick),font=f(17),fill='#a9b9ca')
 points=[]
 for i,r in enumerate(rs):
  x=left+i*(right-left)/(len(rs)-1);y=bottom-r['remoteReadMs']/ymax*(bottom-top);points.append((x,y))
 d.line(points,fill='#6be5bc',width=3)
 for x,y in points:d.ellipse((x-5,y-5,x+5,y+5),fill='#6be5bc')
 d.text((95,730),'Steady turns in execution order (8 per batch)',font=f(20),fill='#a9b9ca')
 d.text((45,785),'Metric: sum of Trace2 exit t_abs for branch.work.remote and remote.origin.url.',font=f(19),fill='white')
 d.text((45,820),'Excludes CLI startup, simulated Replay streaming and the 12 s settling interval.',font=f(19),fill='#a9b9ca')
 im.save(root/f'{label.lower()}.png')
