import json,sys,statistics,random
from pathlib import Path
from PIL import Image,ImageDraw,ImageFont
folder=Path(sys.argv[1]); summary=json.loads((folder/'summary.json').read_text()); raw=[json.loads(x) for x in (folder/'raw.jsonl').read_text().splitlines()]
font='/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf'
def f(n): return ImageFont.truetype(font,n)
labels={'clean':'Clean checkout','committed3':'3 committed additions','mixed':'20 edited + 80 untracked'}
comparisons=[]
for name in labels:
 a=next(x for x in summary['summary'] if x['fixture']==name and x['side']=='before'); b=next(x for x in summary['summary'] if x['fixture']==name and x['side']=='after')
 savings=a['median']-b['median'];spread=max(a['q3']-a['q1'],b['q3']-b['q1'])
 pairs={i:{r['side']:r['ms'] for r in raw if r['fixture']==name and r['iteration']==i} for i in range(1,a['n']+1)}
 deltas=[p['before']-p['after'] for p in pairs.values()]
 rng=random.Random(38707); boot=[]
 for _ in range(10000):
  sample=rng.choices(list(pairs.values()),k=len(pairs));boot.append(statistics.median(p['before'] for p in sample)-statistics.median(p['after'] for p in sample))
 boot.sort()
 comparisons.append({'bootstrap95CI':[boot[250],boot[9749]],'fixture':name,'medianSavingsMs':savings,'maxIqrMs':spread,'savingsExceedSpread':savings>spread,'pairedMedianSavingsMs':statistics.median(deltas)})
for side,sha in [('before',summary['base']),('after',summary['head'])]:
 image=Image.new('RGB',(1100,770),'#f8fafc');d=ImageDraw.Draw(image)
 d.text((35,25),'GIT STATUS — '+side.upper(),font=f(30),fill='#0f172a');d.text((35,72),sha,font=f(18),fill='#334155')
 lines=['Windows Server 2025 • Node '+summary['node']+' • '+summary['git'], 'Real server / WebSocket subscription → first Changes totals response', '32 cold requests per fixture; paired alternating order; one warm-up excluded']
 for i,line in enumerate(lines):d.text((35,112+i*30),line,font=f(19),fill='#334155')
 for j,name in enumerate(labels):
  row=next(x for x in summary['summary'] if x['fixture']==name and x['side']==side);y=230+j*145
  d.line((35,y-10,1060,y-10),fill='#cbd5e1',width=1);d.text((35,y),labels[name],font=f(23),fill='#0f172a')
  d.text((35,y+38),f"Median {row['median']:.1f} ms    IQR {row['q1']:.1f}–{row['q3']:.1f} ms",font=f(23),fill='#0f172a')
  d.text((35,y+75),f"Range {row['min']:.1f}–{row['max']:.1f} ms   |   Git processes {min(row['gitCounts'])}–{max(row['gitCounts'])}",font=f(18),fill='#475569')
 d.text((35,695),'Identical complete status on every pair: '+str(summary['identical']),font=f(20),fill='#0f172a')
 d.text((35,728),'Changes totals: 0 / 3 / 100 insertions; all real index hashes unchanged',font=f(20),fill='#0f172a')
 image.save(folder/(side+'.png'))
 text={'commit':sha,'environment':lines,'measurements':[r for r in summary['summary'] if r['side']==side],'statusIdenticalEveryPair':summary['identical'],'allIndexHashesUnchanged':summary['indexUnchanged']}
 (folder/(side+'.json')).write_text(json.dumps(text,indent=2))
(folder/'comparison.json').write_text(json.dumps(comparisons,indent=2))
print(json.dumps(comparisons,indent=2))
# A responsive chart uses exactly the same recorded medians and quartiles.
maxval=max(r['q3'] for r in summary['summary'])*1.1
svg=['<svg viewBox="0 0 700 340" role="img" aria-label="Status request median and interquartile range, milliseconds" style="width:100%;height:340px">']
for j,name in enumerate(labels):
 y=35+j*100;svg.append(f'<text x="0" y="{y}" fill="var(--foreground)" font-size="15">{labels[name]}</text>')
 for k,side in enumerate(['before','after']):
  r=next(r for r in summary['summary'] if r['fixture']==name and r['side']==side);yy=y+22+k*25;color='var(--chart-1)' if k==0 else 'var(--chart-2)'
  x=lambda value:190+value/maxval*390
  svg.append(f'<text x="0" y="{yy+4}" fill="var(--muted-foreground)" font-size="13">{side.title()}</text><line x1="{x(r["q1"])}" y1="{yy}" x2="{x(r["q3"])}" y2="{yy}" stroke="{color}" stroke-width="8"/><circle cx="{x(r["median"])}" cy="{yy}" r="6" fill="{color}"/><text x="600" y="{yy+4}" fill="var(--foreground)" font-size="13">{r["median"]:.1f} ms</text>')
svg.append('</svg>')
(folder/'chart.html').write_text('<!doctype html><html><body><p>Cold status request: median (dot) and interquartile range (line). 32 samples per fixture and commit, Windows Server 2025.</p>'+''.join(svg)+'</body></html>')
from collections import Counter
patterns={
 'separate_index':lambda c:c==['rev-parse','--git-path','index'],
 'separate_common_dir':lambda c:c==['rev-parse','--git-common-dir'],
 'separate_root':lambda c:c==['rev-parse','--show-toplevel'],
 'batched_paths':lambda c:c==['rev-parse','--path-format=absolute','--git-path','index','--git-common-dir','--show-toplevel'],
}
path_counts=[]
for name in labels:
 for side in ['before','after']:
  r=[r for r in raw if r['fixture']==name and r['side']==side and r['iteration']>0]
  path_counts.append({'fixture':name,'side':side,**{key:dict(Counter(sum(predicate(c) for c in row['commands']) for row in r)) for key,predicate in patterns.items()}})
(folder/'path-lookup-counts.json').write_text(json.dumps(path_counts,indent=2))
print(json.dumps(path_counts,indent=2))
