# Record the live stdout of the real API driver as a readable video.
import subprocess,sys,threading,time,textwrap
from pathlib import Path
from PIL import Image,ImageDraw,ImageFont
root,side,sha=sys.argv[1:]
folder=Path(__file__).parent/(side+'-recording-'+str(time.time_ns()));folder.mkdir()
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',20)
lines=['Live server API output | '+side.upper(), 'Commit '+sha, 'Linux | Codex CLI 0.171.0 | local Responses fixture', '']
p=subprocess.Popen(['node',str(Path(__file__).parent/'prove.mjs'),root,side,sha],stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True)
raw=[]
def read():
 for line in p.stdout:
  raw.append(line)
  lines.extend(textwrap.wrap(line.rstrip(),width=126,replace_whitespace=False) or [''])
threading.Thread(target=read,daemon=True).start()
v=subprocess.Popen(['ffmpeg','-loglevel','error','-y','-f','rawvideo','-pixel_format','rgb24','-video_size','1920x1080','-framerate','2','-i','-','-c:v','libx264','-preset','fast','-crf','20','-pix_fmt','yuv420p',str(folder/'api-recording.mp4')],stdin=subprocess.PIPE)
while True:
 im=Image.new('RGB',(1920,1080),'#10151e');d=ImageDraw.Draw(im)
 for n,line in enumerate(lines[-43:]): d.text((30,22+n*24),line,font=font,fill='#e8edf4')
 v.stdin.write(im.tobytes())
 if p.poll() is not None: break
 time.sleep(.5)
for _ in range(4):v.stdin.write(im.tobytes())
v.stdin.close();v.wait();im.save(folder/'completed-api-output.png');(folder/'console.txt').write_text(''.join(raw))
print(str(folder),flush=True)
sys.exit(p.returncode)
