import subprocess,sys,os,time,json,select,textwrap
from PIL import Image,ImageDraw,ImageFont
root=os.path.dirname(os.path.abspath(__file__))
side=sys.argv[1]; checkout=sys.argv[2]; count=sys.argv[3]
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',19)
large=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',26)
sha=subprocess.check_output(['git','-C',checkout,'rev-parse','--short=10','HEAD'],text=True).strip()
lines=[]
def add(s):
 lines.extend(textwrap.wrap(s,105,replace_whitespace=True) or [''])
def frame(done=False):
 im=Image.new('RGB',(1440,900),'#10151e');d=ImageDraw.Draw(im)
 d.text((32,24),f'Cursor text generation | {side.upper()} | {sha}',font=large,fill='#f1f5f9')
 d.text((32,70),'Linux / Node 26 / real @cursor/sdk 1.5.0 / Cursor Auto (default)',font=font,fill='#9bacbf')
 d.text((32,104),'Production generateCommitMessage / identical 60 KB patch / fresh temporary stores',font=font,fill='#9bacbf')
 d.line((32,145,1408,145),fill='#354357')
 for i,line in enumerate(lines[-25:]):
  color='#ffb4a9' if any(x in line for x in ['ERROR','createPlan','PREAMBLE']) else '#c6e8d4' if 'SUCCESS' in line else '#d6e0ee'
  d.text((32,166+i*26),line,font=font,fill=color)
 d.text((32,855),'Completed' if done else 'Live production-service run; SDK options and output observed without behavior overrides',font=font,fill='#9bacbf')
 return im
p=subprocess.Popen(['node',root+'/driver.mjs',checkout,side,count],stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True,bufsize=1)
ff=subprocess.Popen(['ffmpeg','-v','error','-y','-f','rawvideo','-pix_fmt','rgb24','-s','1440x900','-r','2','-i','-','-c:v','libx264','-preset','veryfast','-crf','24','-pix_fmt','yuv420p',root+'/'+side+'.mp4'],stdin=subprocess.PIPE)
log=open(root+'/'+side+'-recording.log','w')
last=0
while True:
 if select.select([p.stdout],[],[],0.05)[0]:
  line=p.stdout.readline()
  if line:
   log.write(line);log.flush()
   try:
    e=json.loads(line)
    ev=e['event']
    if ev=='Agent.create': add(f"Agent.create mode={e['mode']} tools={e['tools']} sandbox={e['sandbox']}")
    elif ev=='run.result':
     r=e['result'];add('SDK reply: '+str(r.get('result','')))
    elif ev=='run.conversation':
     for t in e['conversation']:
      for s in t.get('turn',{}).get('steps',[]):
       if s['type']=='toolCall': add('TOOL CALL: '+json.dumps(s['message']))
    elif ev=='generation.error': add('ERROR: '+e['error'])
    elif ev=='generation.success': add('SUCCESS: '+json.dumps(e['result']))
   except (ValueError,KeyError):
    if line.startswith(('RUN ','Evidence saved:')): add(line.strip())
  elif p.poll() is not None: break
 if time.monotonic()-last>=0.5:
  ff.stdin.write(frame().tobytes());last=time.monotonic()
 if p.poll() is not None and not select.select([p.stdout],[],[],0)[0]: break
for _ in range(6):ff.stdin.write(frame(True).tobytes())
frame(True).save(root+'/'+side+'.png')
ff.stdin.close();ff.wait();p.wait();log.close()
print(side,'recorded',p.returncode)
