import pathlib,json,collections,textwrap,subprocess,math
from PIL import Image,ImageDraw,ImageFont
ROOT=pathlib.Path(__file__).parent
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',16)
small=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',14)
big=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf',28)
SHAS={'before':'ab3a6219e5b49c46eeff06150c2193f593f559a9','after':'737c450d260951e3794b999a2533c02567f19f5a'}
NAMES=['orchestrationV2.ProviderCommitBatch.flush','Orchestrator.handleRunUpdate','Orchestrator.deliverDeferredSteers']
summary={}
for side in ['before','after']:
 run=pathlib.Path((ROOT/(side+'-latest.txt')).read_text());out=ROOT/side;out.mkdir(exist_ok=True)
 rows=[json.loads(l) for l in (run/'data/userdata/logs/server.trace.ndjson').read_text().splitlines()]
 # Keep trace topology and timing verbatim; omit attributes, events, errors, and links that may contain local paths.
 safe=[{k:v for k,v in r.items() if k in ['type','name','traceId','spanId','parentSpanId','kind','startTimeUnixNano','endTimeUnixNano','durationMs']} for r in rows]
 (out/'trace-topology.ndjson').write_text(''.join(json.dumps(r)+'\n' for r in safe))
 metrics=[]
 lines=['Real T3 server trace export analysis',side.upper()+' '+SHAS[side],'Linux x86_64 | Node 24.23.0 | fresh synthetic project/data','Three sequential devReplay/default turns: first, second, third','Wait for six run-update reactions; stop server; group exported spans.','']
 for name in NAMES:
  selected=[r for r in rows if r['name']==name];ids=set(r['traceId'] for r in selected);counts=collections.Counter(r['traceId'] for r in selected)
  m={'name':name,'operations':len(selected),'distinctTraces':len(ids),'rootSpans':sum(not r.get('parentSpanId') for r in selected),'maxOperationsPerTrace':max(counts.values(),default=0)};metrics.append(m)
  lines.extend([name,'  '+str(m['operations'])+' operations / '+str(m['distinctTraces'])+' distinct traces / '+str(m['rootSpans'])+' root spans','  Most operations sharing one trace: '+str(m['maxOperationsPerTrace'])])
  if len(ids)==1:
   tid=next(iter(ids));group=[r for r in rows if r['traceId']==tid];roots=[r['name'] for r in group if not r.get('parentSpanId')]
   lines.append('  Inherited root: '+', '.join(roots)+' ('+str(len(group))+' exported spans)')
 lines.extend(['','Source: real server.trace.ndjson; names, trace IDs, parent IDs and times preserved.','Attributes/events omitted from shared export to keep local paths private.','Delegated child with outliving background work: not exercised.'])
 (out/'analysis.txt').write_text('\n'.join(lines)+'\n');summary[side]=metrics
 im=Image.new('RGB',(1440,790),'#10151f');d=ImageDraw.Draw(im);d.text((34,25),lines[0],font=big,fill='#ffffff')
 y=80
 for line in lines[1:]:
  d.text((34,y),line,font=font,fill=('#fb9b91' if side=='before' else '#83e1b1') if 'operations /' in line else '#d4dce9');y+=28
 im.save(out/'trace-analysis.png')
 # Render the recorded stdout events as a terminal recording, preserving event timing.
 events=[json.loads(l) for l in (run/'session.cast').read_text().splitlines()[1:]]
 events.append([events[-1][0]+.5,'o','\r\n'+(out/'analysis.txt').read_text().replace('\n','\r\n')])
 fps=4;duration=events[-1][0]+8
 proc=subprocess.Popen(['ffmpeg','-loglevel','error','-y','-f','rawvideo','-vcodec','rawvideo','-pix_fmt','rgb24','-s','1440x790','-r',str(fps),'-i','-','-an','-c:v','libx264','-preset','veryfast','-crf','24','-pix_fmt','yuv420p',str(out/'cli-recording.mp4')],stdin=subprocess.PIPE)
 terminal=[];index=0
 for frame in range(math.ceil(duration*fps)):
  now=frame/fps
  while index<len(events) and events[index][0]<=now:
   terminal.extend(line for raw in events[index][2].replace('\r','').split('\n') for line in (textwrap.wrap(raw,136,replace_whitespace=False) or ['']))
   index+=1
  im=Image.new('RGB',(1440,790),'#10151f');d=ImageDraw.Draw(im)
  d.text((24,16),side.upper()+' | real CLI stdout | Node 24.23.0 | '+SHAS[side][:10]+' | '+str(round(now,1))+' s',font=font,fill='#83c5ff')
  for row,line in enumerate(terminal[-33:]): d.text((24,54+row*21),line,font=small,fill='#e0e5ee')
  proc.stdin.write(im.tobytes())
 proc.stdin.close();assert proc.wait()==0
 for name in ['commands.txt','session.cast']: (out/name).write_bytes((run/name).read_bytes())
(ROOT/'metrics.json').write_text(json.dumps(summary,indent=2))
print(json.dumps(summary,indent=2))
