#!/usr/bin/env python3
"""Analyze shareable structural spans from driver.py output."""
import pathlib,sys,json,collections
root=pathlib.Path(sys.argv[1]); summary={}
for side in ['before','after']:
 rows=[json.loads(l) for l in (root/side/'trace-structure.ndjson').read_text().splitlines()]
 targets=json.loads((root/side/'summary.json').read_text())
 inbound=[r for r in rows if r.get('httpPath') in ['/mcp','/api/preview/tunnel']][:15]
 summary[side]={'targets':targets,'first15InboundRequests':{'spans':len(inbound),'traces':len({r['traceId'] for r in inbound}),'roots':sum(not r.get('parentSpanId') for r in inbound)},'periodicSweepStartTimes':{name:[r['startTimeUnixNano'] for r in rows if r['name']==name] for name in ['ThreadSettlementServiceV2.sweep','PullRequestSyncReactor.sweep']}}
 before=side=='before'
 assert all(s['ticks']>1 and ((s['traces']==1 and s['roots']==0) if before else (s['traces']==s['ticks'] and s['roots']==s['ticks'])) for s in targets.values()),(side,targets)
 assert len(inbound)==15 and len({r['traceId'] for r in inbound})==15 and all(not r.get('parentSpanId') for r in inbound)
 assert (root/side/'final.png').read_bytes()==(root/side/'final-stability.png').read_bytes()
print(json.dumps(summary,indent=2))
(root/'analysis.json').write_text(json.dumps(summary,indent=2))
