#!/usr/bin/env python3
"""Render measured scenario output; usage: summarize.py BASE.json HEAD.json OUTPUT_DIR."""
import sys,json,statistics,pathlib,html,subprocess
base=json.load(open(sys.argv[1])); head=json.load(open(sys.argv[2])); out=pathlib.Path(sys.argv[3])
shas=['f92c5e8f98246ea5537e3ea002fb7bb8ffd84451','81d571a8d11578af0356dd19a4ba1c2c3da247b2']
summary={}
for side,d,sha in zip(['before','after'],[base,head],shas):
    xs=d['fullBranchMs']; ui=[r['uiMs'] for r in d['runs']]
    perfile=[q['ms'] for r in d['runs'] for q in r['requests'] if q['payload'].get('file')]
    sources=[s for r in d['runs'] for q in r['requests'] if not q['payload'].get('file') for s in q.get('sources',[]) if s['kind']=='branch-range']
    files=[s.get('files',[]) for s in sources]
    paths=[sorted(f['path'] for f in fs) for fs in files]
    summary[side]={'commit':sha,'fullBranchMs':xs,'medianMs':statistics.median(xs),'rangeMs':[min(xs),max(xs)],'spreadMs':max(xs)-min(xs),'uiCompleteMs':ui,'uiMedianMs':statistics.median(ui),'perFileMs':perfile,'perFileMedianMs':statistics.median(perfile) if perfile else None,'warningRuns':sum(r['warningSeen'] for r in d['runs']),'returnedFileCounts':[len(fs) for fs in files],'stablePaths':all(p==paths[0] for p in paths),'paths':paths[0] if paths else []}
summary['sameReturnedPaths']=summary['before']['paths']==summary['after']['paths']
summary['medianImprovementMs']=summary['before']['medianMs']-summary['after']['medianMs']
summary['improvementExceedsBothSpreads']=summary['medianImprovementMs']>max(summary[s]['spreadMs'] for s in ['before','after'])
(out/'comparison.json').write_text(json.dumps(summary,indent=2)+'\n')
lines=['Issue 38285 — real web app, same Linux x86_64 host, Chromium 156, 1280 × 800 light theme','Fresh isolated server per commit; Replay (dev) showcase; identical deterministic fixture','6 generated schemas × 30,000 declarations + 3,000 small changed files','Open Changes (feature vs Automatic → main), then Refresh diff five times.','Browser WebSocket send → successful response, measured with performance.now().','']
for side in ['before','after']:
    d=summary[side]
    lines += [side.upper()+' '+d['commit'],'Full-branch RPC seconds: '+', '.join(f'{x/1000:.3f}' for x in d['fullBranchMs']),f"Median {d['medianMs']/1000:.3f}s; range {d['rangeMs'][0]/1000:.3f}–{d['rangeMs'][1]/1000:.3f}s; spread {d['spreadMs']/1000:.3f}s",'Refresh-to-ready seconds: '+', '.join(f'{x/1000:.3f}' for x in d['uiCompleteMs']),f"Slow-request warning observed in {d['warningRuns']}/5 refreshes; returned file counts {d['returnedFileCounts']}",'']
lines += [f"Median improvement {summary['medianImprovementMs']/1000:.3f}s exceeds both within-side spreads: {summary['improvementExceedsBothSpreads']}",f"Both commits returned the same file paths: {summary['sameReturnedPaths']}",'The diff algorithm may choose different valid hunks; exact patch identity is not claimed.']
(out/'measurement.txt').write_text('\n'.join(lines)+'\n')
for side in ['before','after']:
    d=summary[side]; color='#b54628' if side=='before' else '#16734c'; maxms=max(summary['before']['fullBranchMs']+summary['after']['fullBranchMs'])
    svg=['<svg xmlns="http://www.w3.org/2000/svg" width="1100" height="680"><rect width="1100" height="680" fill="#f8fafc"/>','<g font-family="DejaVu Sans, sans-serif" fill="#152435">']
    def text(x,y,t,size=20):svg.append(f'<text x="{x}" y="{y}" font-size="{size}">{html.escape(t)}</text>')
    text(40,48,side.upper()+' — Changes / Refresh diff',30);text(40,83,d['commit'],19)
    text(40,125,'Real web app • Linux x86_64 • Chromium 156 • 1280 × 800 • light theme',18)
    text(40,154,'Same synthetic feature branch: 6 large reordered schemas + 3,000 small files',18)
    text(40,198,'review.getDiffPreview — full-branch request (seconds)',21)
    for i,x in enumerate(d['fullBranchMs']):
        y=222+i*58;text(40,y+26,f'Run {i+1}',19)
        w=max(3,x/maxms*740);svg.append(f'<rect x="132" y="{y}" width="{w}" height="34" rx="4" fill="{color}"/>');text(145+w,y+25,f'{x/1000:.3f}s',19)
    text(40,553,f"Median {d['medianMs']/1000:.3f}s   |   Spread {d['spreadMs']/1000:.3f}s   |   n = 5",24)
    text(40,592,f"Slow-request warning: {d['warningRuns']}/5 refreshes. Same 3,006 file paths on both commits.",19)
    text(40,632,'Measured from browser WebSocket send to successful response; UI driven by scenario.',17)
    svg.append('</g></svg>');p=out/f'{side}-measurement.svg';p.write_text(''.join(svg));subprocess.run(['convert',str(p),str(out/f'{side}-measurement.png')],check=True)
print('\n'.join(lines))
