import json,pathlib,statistics,sys
root=pathlib.Path(sys.argv[1]); result={}
for side in ['base','head']:
    if not (root/side).exists():continue
    folder=sorted((root/side).glob('measure-*'))[-1]
    runs=[]
    for trace in sorted(folder.glob('trace-*.jsonl')):
        records=[]
        for line in trace.read_text(encoding='utf-8-sig').splitlines():
            try: r=json.loads(line)
            except: continue
            if 'spanId' in r and 'durationMs' in r: records.append(r)
        spans={r['spanId']:r for r in records}
        def ancestor(r,id):
            seen=set()
            while r.get('parentSpanId') and r['parentSpanId'] not in seen:
                p=r['parentSpanId'];seen.add(p)
                if p==id:return True
                r=spans.get(p,{})
            return False
        lookups=[]
        for r in records:
            if r['name']=='branchPullRequest':
                children=[s for s in records if s['name']=='runGitCommand' and ancestor(s,r['spanId'])]
                caller=spans.get(r.get('parentSpanId'),{}).get('name');lookups.append({'caller':caller,'spanId':r['spanId'],'startTimeUnixNano':r['startTimeUnixNano'],'durationMs':r['durationMs'],'gitProcessCount':len(children),'gitSpanIds':[s['spanId'] for s in children]})
        lookups.sort(key=lambda r:int(r['startTimeUnixNano']))
        discovery=[r for r in lookups if r['caller']=='ThreadPullRequestServiceV2.synchronize']
        max_git=max((r['gitProcessCount'] for r in lookups),default=0)
        full=[r for r in lookups if r['gitProcessCount']==max_git]
        process_file=folder/trace.name.replace('trace-','git-processes-')
        native=[json.loads(s) for s in process_file.read_text().splitlines()] if process_file.exists() else []
        runs.append({'run':trace.stem,'lookups':lookups,'discoveryGitProcessTotal':sum(r['gitProcessCount'] for r in discovery),'fullLookupGitProcessTotal':sum(r['gitProcessCount'] for r in full),'maximumGitProcessesPerLookup':max_git,'fullLookupCount':len(full),'startupLookupMs':full[0]['durationMs'] if full else None,'secondSweepLookupMs':[r['durationMs'] for r in full[1:]],'discoveryStartupLookupMs':discovery[0]['durationMs'] if discovery else None,'discoverySecondSweepLookupMs':[r['durationMs'] for r in discovery[1:]],'nativeGitProcessStarts':sum(r['event']=='start' for r in native),'runGitCommandSpans':sum(r['name']=='runGitCommand' for r in records)})
        safe=[{k:r[k] for k in ['type','name','spanId','parentSpanId','startTimeUnixNano','endTimeUnixNano','durationMs'] if k in r} for r in records]
        (folder/(trace.stem+'-public.json')).write_text(json.dumps(safe,indent=2))
    result[side]={'runs':runs,'snapshots':json.loads((folder/'results.json').read_text())}
for side,data in result.items():
    summaries={}
    for phase in ['startup','secondSweep']:
        values=[r['startupLookupMs'] if phase=='startup' else statistics.median(r['secondSweepLookupMs']) for r in data['runs']]
        summaries[phase]={'runMediansMs':values,'medianMs':statistics.median(values),'spreadMs':max(values)-min(values)}
    data['summary']=summaries
print(json.dumps(result,indent=2))
