"""Compare the two real-client exports and produce a self-contained report. No test runner."""
from pathlib import Path
import json,statistics,hashlib,sys,html
p=Path(sys.argv[1]);b=json.loads((p/'base-browser-results.json').read_text());h=json.loads((p/'head-browser-results.json').read_text())
assert b['environment']==h['environment']
rows=[]
for k in range(4):
 bs=[s for s in b['samples'] if s['kind']==k];hs=[s for s in h['samples'] if s['kind']==k]
 assert len(bs)==len(hs)==9
 for x,y in zip(bs,hs):
  assert x['input']==y['input'] and x['output']==y['output']
  assert len(x['output'])==len(set(x['output']))==x['count']
 a=[x['ms'] for x in bs];c=[x['ms'] for x in hs]
 row=dict(label=bs[0]['label'],baseMedian=statistics.median(a),headMedian=statistics.median(c),baseMin=min(a),baseMax=max(a),headMin=min(c),headMax=max(c),baseSamples=a,headSamples=c,identicalOrder=True,outputSha256=hashlib.sha256(json.dumps(bs[0]['output'],separators=(',',':')).encode()).hexdigest())
 row['medianImprovement']=row['baseMedian']-row['headMedian'];row['baseSpread']=max(a)-min(a);row['headSpread']=max(c)-min(c)
 row['improvementExceedsBothSpreads']=row['medianImprovement']>max(row['baseSpread'],row['headSpread'])
 rows.append(row)
result=dict(environment=b['environment'],cpu='AMD EPYC 4465P; 8 logical CPUs allocated',baseSha='fdce61c02203278a4b200798e50a714843a0574d',headSha='84c705f03b57208b2bae6810334fa822001d93d5',rows=rows)
(p/'comparison.json').write_text(json.dumps(result,indent=2))
# SVG bars show medians; whiskers show the complete min/max range, including outliers.
svg=['<svg viewBox="0 0 700 365" role="img" aria-label="Median ordering time in milliseconds with full min-max ranges" style="width:100%;height:365px">']
scale=lambda t:220+t*2.7
for t in [0,25,50,75,100,125,150]:
 x=scale(t);svg.append(f'<path d="M{x},12 V330" stroke="var(--border)"/><text x="{x}" y="350" text-anchor="middle" fill="var(--muted-foreground)" font-size="11">{t}</text>')
for i,r in enumerate(rows):
 y=35+i*80
 label=r['label'].replace('source files:','files ·')
 svg.append(f'<text x="0" y="{y+12}" fill="var(--foreground)" font-size="12">{label}</text>')
 for side,dy,color in [('base',0,'var(--chart-1)'),('head',25,'var(--chart-2)')]:
  yy=y+dy;median=r[side+'Median'];lo=r[side+'Min'];hi=r[side+'Max']
  svg.append(f'<rect x="220" y="{yy-7}" width="{median*2.7}" height="14" rx="2" fill="{color}" opacity=".7"/><path d="M{scale(lo)},{yy} H{scale(hi)} M{scale(lo)},{yy-4} V{yy+4} M{scale(hi)},{yy-4} V{yy+4}" stroke="var(--foreground)" stroke-width="1"/><circle cx="{scale(median)}" cy="{yy}" r="3" fill="var(--foreground)"/>')
svg.append('</svg>')
trs=''.join(f'<tr><td>{r["label"].replace("source files:","files ·")}</td><td>{r["baseMedian"]:.1f}<small>{r["baseMin"]:.1f}–{r["baseMax"]:.1f}</small></td><td>{r["headMedian"]:.1f}<small>{r["headMin"]:.1f}–{r["headMax"]:.1f}</small></td><td>{"Yes" if r["improvementExceedsBothSpreads"] else "No"}</td></tr>' for r in rows)
report='''<!doctype html><html><head><meta charset="utf-8"><style>
:root{font-family:var(--font-sans,system-ui)}body{margin:0;color:var(--foreground)}h2{font-size:22px;margin:8px 0}p{font-size:13px;line-height:1.5;margin:8px 0;color:var(--muted-foreground)}.legend{display:flex;gap:24px;font-size:12px;margin:16px 0 0}.dot{width:9px;height:9px;display:inline-block;margin-right:6px;border-radius:50%}table{border-collapse:collapse;width:100%;font-size:12px}td,th{text-align:left;border-bottom:1px solid var(--border);padding:10px 5px}small{display:block;color:var(--muted-foreground);margin-top:4px}th{font-weight:500}code{font-family:var(--font-mono,monospace);font-size:12px}</style></head><body>
<h2>Real Code tab: diff ordering time</h2><p>Linux x86_64 · Chrome 158 · AMD EPYC 4465P · 8 logical CPUs · 1280×800 · light theme</p>
<p>Nine new diff loads per graph per commit, after two warm-up rounds. Timed only <code>orderDiffFilesForReview</code> in the real Code tab. Synthetic PR replies crossed the app's HTTP/RPC boundary. No cached model reuse.</p>
<div class="legend"><span><i class="dot" style="background:var(--chart-1)"></i>Before · fdce61c022</span><span><i class="dot" style="background:var(--chart-2)"></i>After · 84c705f03b</span><span>Bar: median · whisker: min–max · ms</span></div>
'''+''.join(svg)+f'''<table><thead><tr><th>Graph</th><th>Before median<small>full range, ms</small></th><th>After median<small>full range, ms</small></th><th>Gain &gt; both spreads</th></tr></thead><tbody>{trs}</tbody></table>
<p>All 36 paired inputs and all 36 complete output orders are exactly equal. For 2,000 files the median gains are 101.2 ms (chain) and 107.7 ms (cycle), exceeding both sides' full spreads. The 1,000-file gains do not exceed the base's full spread.</p>
<p>These are function timings inside the real app, not total tab-load latency. Network, parsing and rendering are excluded from the timed region. Asymptotic time and space bounds are not proved by these samples.</p></body></html>'''
(p/'measurement-report.html').write_text(report)
text='Real Code tab ordering: 9 measurements per case per commit\nLinux x86_64 / Chrome 158 / 1280x800 / light\n'
for r in rows:text+=f"{r['label']}: base {r['baseMedian']:.1f} ms [{r['baseMin']:.1f}, {r['baseMax']:.1f}], head {r['headMedian']:.1f} ms [{r['headMin']:.1f}, {r['headMax']:.1f}]. Identical order: yes. Improvement exceeds both full spreads: {r['improvementExceedsBothSpreads']}.\n"
(p/'measurement-output.txt').write_text(text);print(text)
