from pathlib import Path
import subprocess,os,sys,textwrap,time,json,re
from PIL import Image,ImageDraw,ImageFont
R=Path(__file__).parent;side=sys.argv[1];driver=sys.argv[2];stamp=str(int(time.time()));dest=R/('capture-'+side+'-'+driver+'-'+stamp);dest.mkdir()
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',19)
titlefont=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',23)
sha='ea05ea5e2af2' if side=='base' else '7379003b32a5'
ff=subprocess.Popen(['ffmpeg','-y','-loglevel','error','-f','rawvideo','-pix_fmt','rgb24','-s','1600x1000','-r','4','-i','-','-an','-c:v','libx264','-preset','fast','-crf','20','-pix_fmt','yuv420p',str(dest/'recording.mp4')],stdin=subprocess.PIPE)
lines=[];events=[];start=time.monotonic();last=None
p=subprocess.Popen([sys.executable,'-u',str(R/(driver+'.py'))],env={**os.environ,'SIDE':side},stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True)
with (dest/'transcript.txt').open('w') as f:
 for line in p.stdout:
  line=line.replace(str(R),'<scratch>').replace(str(Path.home()),'<user-home>')
  # Remove user service's unrelated home detail from the output capture.
  line=line.replace('%h/.t3','<other-home>')
  f.write(line);f.flush();events.append({'seconds':round(time.monotonic()-start,3),'text':line})
  print(line,end='',flush=True)
  for l in line.rstrip('\n').splitlines() or ['']:
   lines.extend(textwrap.wrap(l, width=128,replace_whitespace=False,drop_whitespace=False) or [''])
  im=Image.new('RGB',(1600,1000),'#10151d');dr=ImageDraw.Draw(im)
  dr.text((30,20),f'{side.upper()} | {sha} | Linux x64 | real {driver} CLI output',font=titlefont,fill='#8bc6ff')
  dr.text((30,62),'Fresh isolated home; synthetic project; absolute paths redacted. Pause to inspect.',font=font,fill='#a8b4c4')
  dr.line((30,100,1570,100),fill='#344455')
  for i,l in enumerate(lines[-32:]):dr.text((30,118+i*26),l,font=font,fill=('#9ee5b1' if l.startswith('$') else '#e3e9ef'))
  ff.stdin.write(im.tobytes());last=im
p.wait()
if last:
 for _ in range(12):ff.stdin.write(last.tobytes())
 last.save(dest/'final.png')
ff.stdin.close();ff.wait();(dest/'events.json').write_text(json.dumps(events,indent=2));print('CAPTURE '+str(dest)+' exit='+str(p.returncode))
sys.exit(p.returncode)
