import pathlib,json,sys,statistics,textwrap,subprocess,math
from PIL import Image,ImageDraw,ImageFont
root=pathlib.Path(__file__).resolve().parent
run=pathlib.Path(sys.argv[1]); side=run.name.split('-')[0]; out=root/'public'; out.mkdir(exist_ok=True)
spans=[]
for l in (run/'data/userdata/logs/server.trace.ndjson').open():
 try:x=json.loads(l)
 except:continue
 if x.get('name') in ['CheckpointService.captureBaseline','CheckpointService.withCaptureLock','ProviderTurnStartService.start']:
  spans.append({k:x[k] for k in ['name','traceId','spanId','parentSpanId','startTimeUnixNano','endTimeUnixNano','durationMs'] if k in x}|{'exit':x['exit']['_tag']})
spans.sort(key=lambda x:int(x['startTimeUnixNano']))
baselines=[s for s in spans if s['name']=='CheckpointService.captureBaseline']
rows=json.loads((run/'results.json').read_text()); events=json.loads((run/'recording.json').read_text())
assert len(baselines)==7, len(baselines)
for i,r in enumerate(rows):
 b=baselines[2+i*2]; a=baselines[1+i*2]; r['A_baseline_seconds']=a['durationMs']/1000; r['B_baseline_seconds']=b['durationMs']/1000
 r['B_turn_start_seconds']=next(s['durationMs']/1000 for s in spans if s['traceId']==b['traceId'] and s['name']=='ProviderTurnStartService.start')
 end=int(b['endTimeUnixNano']); r['nearest_capture_end_delta_ms']=min(abs(end-int(s['endTimeUnixNano']))/1e6 for s in spans if s['name']=='CheckpointService.withCaptureLock')
skip_count=(run/'server-private.log').read_text().count('baseline skipped after repeated capture timeouts')
assert skip_count==6, skip_count
for r in rows:
 assert r['B_result']['status']=='completed'
assert len({r['B_result']['reply'] for r in rows})==1
# Public exports deliberately contain synthetic CLI results and selected trace fields only.
export={'environment':'Linux x86_64; source server; Replay (dev) showcase; fresh database; 40 x 100 MB random untracked files','side':side,'commit':events[1]['text'].removeprefix('Commit '),'repeated_timeout_skip_messages':skip_count,'rounds':rows,'spans':spans}
(out/f'{side}-measurement.json').write_text(json.dumps(export,indent=2))
lines=[events[0]['text'],events[1]['text'],'Same driver and input bytes on both commits.','Warmup baseline times out at 5 s; post-turn capture times out at 30 s.','Each round: send A --wait; wait 1 s; start fresh B --wait.','']
for r in rows:
 lines.append(f"Round {r['round']}: B baseline {r['B_baseline_seconds']:.3f} s | turn start {r['B_turn_start_seconds']:.3f} s | CLI --wait {r['B_wait_seconds']:.3f} s")
 lines.append(f"         A baseline {r['A_baseline_seconds']:.3f} s | A CLI --wait {r['A_wait_seconds']:.3f} s | B status {r['B_result']['status']}")
for key in ['B_baseline_seconds','B_turn_start_seconds','B_wait_seconds']:
 vals=[r[key] for r in rows]; lines.append(f'{key}: median {statistics.median(vals):.3f} s; range {min(vals):.3f}-{max(vals):.3f} s; spread {max(vals)-min(vals):.3f} s')
lines+=['','All B threads completed with the same recorded showcase reply.',f'Server logged {skip_count} repeated-timeout baseline skips (A and B in all 3 rounds).','Reply excerpt: '+rows[0]['B_result']['reply'].splitlines()[0], 'Selected server spans and full synthetic replies are in the measurement JSON.']
(out/f'{side}-measurement.txt').write_text('\n'.join(lines)+'\n')
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',19); title=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf',30)
def canvas(titletext,ls,footer=''):
 im=Image.new('RGB',(1600,900),'#101820'); d=ImageDraw.Draw(im); d.text((45,35),titletext,font=title,fill='#f5f7fa'); y=100
 for line in ls:
  for w in textwrap.wrap(line,118,replace_whitespace=False) or ['']:
   d.text((45,y),w,font=font,fill='#cfe3ef'); y+=27
 d.text((45,850),footer,font=font,fill='#7cd9af'); return im
canvas(side.upper()+' — real server timing capture',lines,'3 measured rounds | seconds from server spans and CLI wall clock').save(out/f'{side}-measurement.png')
# Replay of timestamped driver output, retaining the full recorded wall-clock timeline.
record=[{'version':2,'width':118,'height':30,'timestamp':0,'env':{'TERM':'xterm-256color'}}]
record += [[e['seconds'],'o',e['text']+'\r\n'] for e in events]
(out/f'{side}-terminal.cast').write_text('\n'.join(json.dumps(x) for x in record)+'\n')
video=out/f'{side}-terminal.mp4'
p=subprocess.Popen(['ffmpeg','-y','-loglevel','error','-f','rawvideo','-pixel_format','rgb24','-video_size','1600x900','-framerate','2','-i','-','-an','-c:v','libx264','-preset','veryfast','-crf','28','-pix_fmt','yuv420p',str(video)],stdin=subprocess.PIPE)
try:
 for frame in range(math.ceil((events[-1]['seconds']+3)*2)):
  t=frame/2; visible=[e['text'] for e in events if e['seconds']<=t]
  wrapped=[]
  for line in visible: wrapped+=textwrap.wrap(line,118) or ['']
  im=canvas(side.upper()+' — captured CLI interaction (real-time playback)',wrapped[-25:],f'Elapsed {t:.1f} s | Timestamped output from the real server driver')
  p.stdin.write(im.tobytes())
finally:p.stdin.close()
assert p.wait()==0
print('\n'.join(lines))
