import sys, subprocess, time, pathlib, json, textwrap
from PIL import Image, ImageDraw, ImageFont
root, out, side, sha = sys.argv[1:]
out = pathlib.Path(out) / (side + '-' + time.strftime('%Y%m%dT%H%M%S'))
out.mkdir()
font = ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf', 17)
lines = []
frames = []
started = time.monotonic()
proc = subprocess.Popen(['node', str(pathlib.Path(__file__).with_name('driver.mjs'))], cwd=root, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, bufsize=1)
def frame():
    im = Image.new('RGB', (1920, 1080), '#101722')
    d = ImageDraw.Draw(im)
    d.text((28, 20), side.upper() + ' | ' + sha + ' | production Cursor usage reader -> real Cursor API', font=font, fill='#83d5fc')
    d.text((28, 48), 'Live stdout capture | Node / FetchHttpClient | fixed date window | no mocks | no UI', font=font, fill='#b3bac6')
    visible=[]
    for line in lines:
        visible.extend(textwrap.wrap(line, width=177, replace_whitespace=False) or [''])
    for index, line in enumerate(visible[-43:]):
        color = '#ff9e9e' if '400' in line or 'BigInt' in line or 'could not be read' in line else '#dce5ef'
        if '"status":200' in line or '"error":null' in line: color='#9be2ae'
        d.text((28, 88+index*22), line, font=font, fill=color)
    name = out / ('frame-%03d.png' % len(frames))
    im.save(name)
    frames.append((time.monotonic()-started, name))
frame()
with (out/'stdout.txt').open('w') as transcript, (out/'timing.jsonl').open('w') as timing:
    for raw in proc.stdout:
        line=raw.rstrip('\n')
        transcript.write(line+'\n'); transcript.flush()
        timing.write(json.dumps({'seconds':round(time.monotonic()-started,3),'stdout':line})+'\n')
        lines.append(line)
        frame()
code=proc.wait()
errors=proc.stderr.read()
if code or errors:
    print('driver stderr:', errors, file=sys.stderr)
    sys.exit(code or 1)
frame()
frames[-1][1].replace(out/'final.png')
frames[-1]=(frames[-1][0], out/'final.png')
with (out/'frames.txt').open('w') as f:
    for index,(stamp,name) in enumerate(frames):
        f.write("file '%s'\n" % name.name)
        duration = max(.1, frames[index+1][0]-stamp) if index+1<len(frames) else 3
        f.write('duration %.3f\n' % duration)
    f.write("file 'final.png'\n")
subprocess.run(['ffmpeg','-hide_banner','-loglevel','error','-f','concat','-safe','0','-i',str(out/'frames.txt'),'-vf','fps=10','-c:v','libx264','-pix_fmt','yuv420p','-movflags','+faststart',str(out/'recording.mp4')], check=True)
print(out)
