import json, statistics, sys, html
from pathlib import Path
root=Path(sys.argv[1])
a=json.loads((root/'base.json').read_text()); b=json.loads((root/'head.json').read_text())
summary={'method':a['method'],'platform':a['platform'],'baseSha':a['sha'],'headSha':b['sha'],'cases':{}}
for case in ['plain','empty','reacted']:
    sides=[]
    for data in [a,b]:
        rows=[r for r in data['rows'] if r['case']==case]
        vals=sorted(r['ms'] for r in rows)
        blocks=[statistics.median(r['ms'] for r in rows if r['block']==k) for k in range(4)]
        q=statistics.quantiles(vals,n=4,method='inclusive')
        sides.append({'n':len(rows),'medianMs':statistics.median(vals),'p25Ms':q[0],'p75Ms':q[2],'blockMediansMs':blocks,'blockSpreadMs':max(blocks)-min(blocks),'requestCounts':sorted(set(len(r['requests']) for r in rows)),'comments':rows[0]['comments'],'reactions':rows[0]['reactions'],'ownReactions':rows[0]['ownReactions']})
    before,after=sides
    gain=before['medianMs']-after['medianMs']
    equal=a['fingerprints'][case]==b['fingerprints'][case]
    summary['cases'][case]={'before':before,'after':after,'gainMs':gain,'gainPercent':100*gain/before['medianMs'],'identicalResultHash':equal,'improvementExceedsBlockSpread':gain>max(before['blockSpreadMs'],after['blockSpreadMs'])}
(root/'summary.json').write_text(json.dumps(summary,indent=2))
print(json.dumps(summary,indent=2))
# A static, shareable measurement capture; all plotted values come from the raw JSON.
width,height=1200,810
s=[f'<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="{height}"><rect width="100%" height="100%" fill="#fff"/>']
def text(x,y,t,size=18,color='#172033'):
    s.append(f'<text x="{x}" y="{y}" font-family="DejaVu Sans" font-size="{size}" fill="{color}">{html.escape(str(t))}</text>')
text(40,45,'Linear comment pagination — real T3 server / live Linear',26)
text(40,78,f'Windows Server 2025 · same leased machine · {len(a["rows"])//3} samples per condition per commit · no added delay',17)
text(40,112,'Before '+a['sha'][:10]+'     After '+b['sha'][:10],18)
text(40,144,f'Bars = pooled median. Lines = four {len(a["rows"])//12}-sample block medians. Two warmups per block.',16)
maxv=max(max(c[z]['blockMediansMs']) for c in summary['cases'].values() for z in ['before','after'])*1.12
for i,(case,c) in enumerate(summary['cases'].items()):
    y=205+i*164
    text(40,y,{'plain':'25 plain comments','empty':'Empty older page','reacted':'25 reacted comments (control)'}[case],20)
    for j,(side,color) in enumerate([('before','#6c78ac'),('after','#209582')]):
        v=c[side]; yy=y+15+j*34; scale=760/maxv
        s.append(f'<rect x="210" y="{yy}" width="{v["medianMs"]*scale}" height="24" rx="3" fill="{color}"/>')
        lo,hi=min(v['blockMediansMs']),max(v['blockMediansMs'])
        s.append(f'<line x1="{210+lo*scale}" y1="{yy+12}" x2="{210+hi*scale}" y2="{yy+12}" stroke="#172033" stroke-width="3"/>')
        text(40,yy+19,side.title(),17)
        text(985,yy+19,f'{v["medianMs"]:.1f} ms',18)
    text(210,y+104,f'{c["gainPercent"]:.1f}% median reduction · calls {c["before"]["requestCounts"]} → {c["after"]["requestCounts"]} · identical response: {c["identicalResultHash"]}',16)
    text(210,y+130,f'Gain {c["gainMs"]:.1f} ms; block spread before {c["before"]["blockSpreadMs"]:.1f} ms / after {c["after"]["blockSpreadMs"]:.1f} ms',15)
text(40,735,'Reaction ownership control: 25 comments, 25 reactions, 25 owned reactions on both commits.',17)
text(40,770,'Scope: authenticated issues.comments RPC. Browser interaction and rendering were not measured.',16)
s.append('</svg>');(root/'comparison.svg').write_text('\n'.join(s))
for side,data in [('before',a),('after',b)]:
    s=[f'<svg xmlns="http://www.w3.org/2000/svg" width="800" height="760"><rect width="100%" height="100%" fill="#fff"/>']
    text(30,42,side.title()+' — Linear comments RPC',25)
    text(30,75,data['sha'][:10],20)
    text(30,109,'Windows Server 2025 · Node v26.13.1 · live Linear',17)
    text(30,137,f'{len(data["rows"])//3} retained samples per condition; four blocks; two warmups per block',16)
    for i,(case,c) in enumerate(summary['cases'].items()):
        v=c[side];y=195+i*153
        text(30,y,{'plain':'25 plain comments','empty':'Empty older page','reacted':'25 reacted comments (control)'}[case],21)
        text(30,y+32,f'Median {v["medianMs"]:.1f} ms · p25 {v["p25Ms"]:.1f} · p75 {v["p75Ms"]:.1f}',18)
        text(30,y+60,f'Block medians: '+', '.join(f'{x:.1f}' for x in v['blockMediansMs'])+' ms',16)
        text(30,y+87,f'Provider calls: {v["requestCounts"]} · comments: {v["comments"]} · own reactions: {v["ownReactions"]}',16)
        s.append(f'<rect x="30" y="{y+100}" width="{v["medianMs"]*680/maxv}" height="17" rx="3" fill="'+('#6c78ac' if side=='before' else '#209582')+'"/>')
    text(30,681,'Entire response SHA-256 matches the other commit in all three conditions.',16)
    text(30,713,'Measurement output from the real server; browser rendering not measured.',16)
    s.append('</svg>');(root/f'{side}.svg').write_text('\n'.join(s))
