import json,pathlib,sys,collections,statistics,datetime

def extract(checkout):
    spans={}
    for p in (pathlib.Path(checkout)/'.t3/userdata/logs').glob('server.trace.ndjson*'):
        for line in p.open():
            try: s=json.loads(line)
            except (ValueError,TypeError): continue
            if s.get('type')=='effect-span': spans[s['spanId']]=s
    def ancestry(s):
        chain=[];seen=set()
        while s and s['spanId'] not in seen:
            seen.add(s['spanId']);chain.append(s);s=spans.get(s.get('parentSpanId'))
        return chain
    sweeps={}
    for s in spans.values():
        if s['name']=='PullRequestWatchReactor.sweep':
            sweeps[s['spanId']]={'start':int(s['startTimeUnixNano'])/1e9,'durationMs':s['durationMs'],'calls':[]}
    sync=[]
    for s in spans.values():
        if s['name']!='VcsProcess.run':continue
        chain=ancestry(s);names=[x['name'] for x in chain]
        if not any('GitLab' in n or 'PullRequestWatchReactor' in n for n in names):continue
        call={'start':int(s['startTimeUnixNano'])/1e9,'durationMs':s['durationMs'],'operation':next((n for n in names if n.startswith('GitLab') and 'Cli.' in n),'GitLab'),'success':s.get('exit',{}).get('_tag')=='Success'}
        sweep=next((a for a in chain if a['name']=='PullRequestWatchReactor.sweep'),None)
        if sweep: sweeps[sweep['spanId']]['calls'].append(call)
        elif any('PullRequestSyncReactor' in n for n in names):sync.append(call)
    return {'sweeps':sorted(sweeps.values(),key=lambda x:x['start']),'linkSyncCalls':sync}

if __name__=='__main__':
    root=pathlib.Path(__file__).parent
    result={side:extract(checkout) for side,checkout in zip(['head','base'],sys.argv[1:])}
    (root/'measurements.json').write_text(json.dumps(result,indent=2))
    for side,data in result.items():
        print(side)
        for s in data['sweeps']:
            if s['calls']:
                print(datetime.datetime.fromtimestamp(s['start'],datetime.timezone.utc).isoformat(),len(s['calls']),round(s['durationMs']),collections.Counter(c['operation'] for c in s['calls']))
