import json, pathlib, statistics, sys
root=pathlib.Path(sys.argv[1])
def quantile(xs,p):
    xs=sorted(xs); i=(len(xs)-1)*p; a=int(i); b=min(a+1,len(xs)-1); return xs[a]+(xs[b]-xs[a])*(i-a)
def stats(xs):
    return {'n':len(xs),'median':statistics.median(xs),'mean':statistics.mean(xs),'min':min(xs),'max':max(xs),'p05':quantile(xs,.05),'p95':quantile(xs,.95),'iqr':quantile(xs,.75)-quantile(xs,.25)} if xs else None
def run(folder):
    j=json.loads((folder/'measurement.json').read_text(encoding='utf-8-sig'))
    scans=[json.loads(x) for x in (folder/'scans.jsonl').read_text(encoding='utf-8-sig').splitlines() if x.strip()] if (folder/'scans.jsonl').exists() else []
    requests=[x for x in scans if x['event']=='scan-request']
    loaded=[x for x in j['launches'] if x['phase'].startswith('load-')]
    result={'commit':j['commit'],'completed':j.get('completed',False),'error':j.get('error'),'osVersion':j['osVersion'],'initialSearch':j.get('initialSearch'),'editorWrite':j.get('editorWrite'),'createdSearch':j.get('createdSearch'),'sameFunction':j.get('sameFunction',False),'turns':len(j['turns']),'turnErrors':[x for x in j['turns'] if x.get('error') or x.get('response',{}).get('status')!='completed'],'preWorkloadLaunchMs':stats([x['elapsedMs'] for x in j['launches'] if x['phase']=='idle']),'idleLaunchMs':stats([x['elapsedMs'] for x in j['launches'] if x['phase']=='idle']) if j.get('idleBeforeIndex') else None,'loadedLaunchMs':stats([x['elapsedMs'] for x in loaded]),'windows':{p:stats([x['elapsedMs'] for x in loaded if x['phase']==p]) for p in sorted(set(x['phase'] for x in loaded))},'totalScanRequests':len(requests),'acceptedScanRequests':sum(x['event']=='scan-result' and x['result'].get('ok',False) for x in scans),'allLaunchesSucceeded':all(x['code']==0 and x['output']=='ok' for x in j['launches'])}
    if 'workloadStart' in j:
        start=j['workloadStart'];end=j.get('workloadEnd',start)
        result['durationSeconds']=(end-start)/1000
        result['firstMinuteScanRequests']=sum(start<=x['at']<start+60000 for x in requests)
        result['workloadScanRequests']=sum(start<=x['at']<end for x in requests)
        result['scanRequestOffsetsSeconds']=[round((x['at']-start)/1000,3) for x in requests]
        io_path=folder/'io.jsonl'
        if io_path.exists():
            io=[json.loads(x) for x in io_path.read_text(encoding='utf-8-sig').splitlines() if x.strip()]
            live=[x for x in io if start<=x['at']<end]
            result['processReadOpsPerSec']=stats([int(x['readOpsPerSec']) for x in live])
            result['processOtherOpsPerSec']=stats([int(x['otherOpsPerSec']) for x in live])
    return result
report={p.name:run(p) for p in sorted(root.iterdir()) if p.is_dir() and (p/'measurement.json').exists()}
(root/'summary.json').write_text(json.dumps(report,indent=2))
print(json.dumps(report,indent=2))
