import subprocess,sys,time,threading,queue,json,textwrap
from pathlib import Path
from PIL import Image,ImageDraw,ImageFont
root=Path(sys.argv[1]); side=sys.argv[2]; checkout=sys.argv[3]; home=sys.argv[4];port=sys.argv[5];sha=sys.argv[6]
out=root/(side+'-recording-'+str(int(time.time())));out.mkdir()
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',20)
large=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',28)
p=subprocess.Popen(['node',str(root/'driver.mjs'),checkout,home,port,side,sha,str(out)],stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True)
q=queue.Queue()
def read():
 for s in p.stdout:q.put(s.rstrip())
threading.Thread(target=read,daemon=True).start()
f=subprocess.Popen(['ffmpeg','-hide_banner','-loglevel','error','-y','-f','rawvideo','-pixel_format','rgb24','-video_size','1600x1000','-framerate','1','-i','-','-c:v','libx264','-preset','ultrafast','-crf','22','-pix_fmt','yuv420p',str(out/'recording.mp4')],stdin=subprocess.PIPE)
lines=[];start=time.monotonic();done=None
while True:
 while not q.empty():
  s=q.get();
  if s.startswith('OUTPUT '):continue
  # Keep the visible status concise; the full API response stays in the raw transcript.
  if 'status:' in s.lower():
   try:
    before,body=s.split(': ',1);data=json.loads(body);s=before+': '+json.dumps({'state':data['state'],'model':data['model']})
   except Exception:pass
  lines.extend(textwrap.wrap(s,120,subsequent_indent='         '))
 img=Image.new('RGB',(1600,1000),'#101722');d=ImageDraw.Draw(img)
 d.text((36,25),f'Dictation disconnect / {side.upper()} / {sha}',font=large,fill='#f2f5fa')
 d.text((36,72),'Live server API capture | Linux | Moonshine streaming tiny | synthetic PCM',font=font,fill='#9bb2c9')
 d.text((36,105),f'Recording elapsed: {time.monotonic()-start:6.1f}s | 1 frame/second | no time acceleration',font=font,fill='#9bb2c9')
 for i,line in enumerate(lines[-27:]):
  color='#f4b3b3' if '"error"' in line or 'transcribing' in line else '#b2e4c0' if '"ready"' in line else '#d8e2ee'
  d.text((36,160+i*29),line,font=font,fill=color)
 f.stdin.write(img.tobytes())
 if p.poll() is not None:
  if done is None:done=time.monotonic()
  if time.monotonic()-done>3:break
 time.sleep(1)
f.stdin.close();f.wait();img.save(out/'final.png')
err=p.stderr.read();
if p.returncode:print(err);sys.exit(p.returncode)
print(out)
