import sys,os,json,subprocess,time,textwrap,datetime
from pathlib import Path
root,side,sha,driver,scratch=sys.argv[1:]
out=Path(scratch)/(side+'-'+datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ'));out.mkdir()
print(out,flush=True)
screen=out/'terminal.txt';video=out/(side+'.mp4')
header=[side.upper()+' | MCP continuation evidence', 'Commit: '+sha,'Real T3 development server | Linux | HTTP MCP | deterministic ACP agents','Fresh synthetic database | 1440 x 1080 | dark terminal','']
def wrap(s):return textwrap.wrap(s,110,replace_whitespace=False,drop_whitespace=False) or ['']
def page(lines):
 content='\n'.join(header+lines)
 tmp=out/'next.txt';tmp.write_text(content);tmp.replace(screen)
 return content
page(['Starting parent agent; waiting for real MCP responses...'])
fflog=open(out/'recording.log','w')
ff=subprocess.Popen(['ffmpeg','-hide_banner','-y','-re','-f','lavfi','-i','color=c=0x101820:s=1440x1080:r=10','-vf',f"drawtext=fontfile=/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf:textfile={screen}:reload=1:expansion=none:fontcolor=0xe6edf3:fontsize=20:line_spacing=10:x=32:y=30",'-c:v','libx264','-preset','ultrafast','-crf','19','-pix_fmt','yuv420p',str(video)],stdin=subprocess.PIPE,stdout=fflog,stderr=fflog)
log=open(out/'driver.log','w')
proc=subprocess.Popen(['node',driver,'drive',root,str(out),side,sha],stdout=log,stderr=subprocess.STDOUT)
start=time.monotonic();last=0;req=None;screen_history=[]
cast=open(out/(side+'.cast'),'w');cast.write(json.dumps({'version':2,'width':110,'height':34,'timestamp':int(time.time()),'title':side+' MCP continuation evidence','env':{'TERM':'xterm-256color'}})+'\n')
try:
 while True:
  ev=out/'events.jsonl'
  if ev.exists():
   rows=ev.read_text().splitlines()
   for line in rows[last:]:
    e=json.loads(line);label=e['label'];v=e['value'];lines=['Recorded at: '+e['time'],'']
    if 'request' in label:req=(label,v)
    if req and ('t3_thread_send' in label):
     lines+=wrap(req[0])+wrap(json.dumps(req[1],ensure_ascii=False))+['']
    lines+=wrap(label)
    if label=='delegate_task response':v={k:v[k] for k in ['childThreadId','status','summary','waitTimedOut'] if k in v}
    if 'wait response' in label:v={k:v[k] for k in ['threadId','runId','status','timedOut'] if k in v}
    if label=='Environment':v={'seed':v['seed']}
    if label=='COMPLETE':lines+=['All calls completed. Exact-ID auto send finished its second turn.','Full original responses are in the accompanying JSONL transcript.']
    else:lines+=wrap(json.dumps(v,ensure_ascii=False))
    if label=='DRIVER ERROR':raise RuntimeError(str(v))
    content=page(lines)
    elapsed=round(time.monotonic()-start,3)
    cast.write(json.dumps([elapsed,'o','\u001b[2J\u001b[H'+content.replace('\n','\r\n')])+'\n');cast.flush()
    screen_history.append({'elapsed':elapsed,'label':label,'text':content})
   last=len(rows)
  if proc.poll() is not None:
   if proc.returncode:raise RuntimeError('Driver failed; see private driver log')
   break
  time.sleep(.05)
 time.sleep(6)
finally:
 ff.communicate(b'q\n',timeout=20);cast.close()
 (out/'screen-history.json').write_text(json.dumps(screen_history,indent=2))
print('Recorded '+str(video),flush=True)
