import json, pathlib, sys, html, subprocess, statistics
p=pathlib.Path(sys.argv[1]); d=json.loads((p/'results/summary.json').read_text())
pub=p/'public';pub.mkdir(exist_ok=True)
def esc(x):return html.escape(str(x))
for side,title,color in [('base','Before: base','#b54b40'),('head','After: fix','#23735b')]:
    a=d[side]; repeats=[v for k,v in sorted(d.items()) if k.startswith(side+'-r')]
    trial=[v['loadedLaunchMs']['median'] for v in repeats]
    idle=[v['idleLaunchMs']['median'] for v in repeats]
    rows=[('Commit',a['commit'][:10]),('Environment','Windows Server 2025 | 4 vCPU | 15.95 GiB RAM'),('Fixture','300,001 nested files | non-Git | synthetic'),('Full workload',f"{a['durationSeconds']:.1f} s | {a['turns']} replay turns | {a['loadedLaunchMs']['n']} launches"),('Post-turn scan requests',str(a['workloadScanRequests'])),('Scan requests in first minute',str(a['firstMinuteScanRequests'])),('Editor write -> searchable','PASS' if a['sameFunction'] else 'FAIL'),('All turns / child launches','PASS' if not a['turnErrors'] and a['allLaunchesSucceeded'] else 'FAIL'),('15-minute launch median',f"{a['loadedLaunchMs']['median']:.2f} ms"),('15-minute launch P05 / P95',f"{a['loadedLaunchMs']['p05']:.2f} / {a['loadedLaunchMs']['p95']:.2f} ms"),('Fresh 3-minute run medians',' / '.join(f'{x:.2f}' for x in trial)+' ms'),('Range of fresh run medians',f'{min(trial):.2f} - {max(trial):.2f} ms'),('Idle medians before first search',' / '.join(f'{x:.2f}' for x in idle)+' ms'),('Process read I/O: median',f"{a['processReadOpsPerSec']['median']:,.1f} operations/s"),('Process read I/O: mean',f"{a['processReadOpsPerSec']['mean']:,.1f} operations/s")]
    svg=['<svg xmlns="http://www.w3.org/2000/svg" width="1100" height="1000" viewBox="0 0 1100 1000">','<rect width="1100" height="1000" fill="#f8fafb"/>','<g font-family="DejaVu Sans, sans-serif">',f'<text x="44" y="60" font-size="30" font-weight="bold" fill="{color}">{esc(title)}</text>','<text x="44" y="94" font-size="18" fill="#4d5965">Real server measurement output | identical workload on both revisions</text>']
    y=135
    for label,value in rows:
        svg.append(f'<rect x="32" y="{y-23}" width="1036" height="39" fill="{"#edf1f4" if (y-135)//40%2==0 else "#f8fafb"}"/>')
        svg.append(f'<text x="44" y="{y}" font-size="17" fill="#45525e">{esc(label)}</text>')
        svg.append(f'<text x="445" y="{y}" font-size="17" fill="#101923" font-weight="bold">{esc(value)}</text>')
        y+=40
    svg.append('<text x="44" y="775" font-size="18" font-weight="bold" fill="#152533">Fresh run launch medians (ms; shared 0-100 scale)</text>')
    for i,x in enumerate(trial):
        y=810+i*35
        svg.append(f'<text x="44" y="{y+16}" font-size="17">Run {i+1}</text><rect x="135" y="{y}" width="{x*7:.2f}" height="23" fill="{color}"/><text x="{145+x*7:.2f}" y="{y+17}" font-size="17">{x:.2f}</text>')
    svg.extend(['<text x="44" y="946" font-size="15" fill="#45525e">I/O counters include non-file I/O. Scan requests count calls to the unchanged native method.</text>','<text x="44" y="973" font-size="15" fill="#45525e">Full-run startup samples overlapped index warmup; only fresh runs provide the idle baseline.</text>','</g></svg>'])
    source=pub/(side+'.svg');source.write_text('\n'.join(svg))
    subprocess.run(['convert',str(source),str(pub/(side+'.png'))],check=True)
print('Rendered measurement output for both revisions.')
