import sys, subprocess, threading, time, textwrap, json
from pathlib import Path
from PIL import Image, ImageDraw, ImageFont
side, container, sha, output = sys.argv[1:]
out=Path(output); out.mkdir(parents=True, exist_ok=False)
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',21)
small=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',18)
lines=[]; lock=threading.Lock(); stop=threading.Event(); events=[]
start=time.monotonic()
def frame():
    im=Image.new('RGB',(1600,1100),'#101820'); d=ImageDraw.Draw(im)
    d.text((28,18),f'{side.upper()} | T3 CLI service install | {sha[:10]}',font=font,fill='#70d6ff')
    d.text((28,54),'Fedora 44 / systemd 259.10 / UID 1000 / isolated cgroup v2 container',font=small,fill='#b2bdca')
    with lock: current=lines[-35:]
    for i,line in enumerate(current): d.text((28,102+i*27),line,font=font,fill='#e8edf2')
    return im
def write(text):
    with lock:
        for line in text.expandtabs(2).splitlines(): lines.extend(textwrap.wrap(line,119,replace_whitespace=False) or [''])
    events.append({'seconds':round(time.monotonic()-start,3),'text':text})
video=subprocess.Popen(['ffmpeg','-y','-loglevel','error','-f','rawvideo','-pixel_format','rgb24','-video_size','1600x1100','-framerate','5','-i','-','-c:v','libx264','-preset','ultrafast','-crf','22','-pix_fmt','yuv420p',str(out/'session.mp4')],stdin=subprocess.PIPE)
def recorder():
    while not stop.is_set():
        video.stdin.write(frame().tobytes()); stop.wait(.2)
thread=threading.Thread(target=recorder); thread.start()
def cmd(label,args):
    write('$ '+label)
    r=subprocess.run(['docker','exec',*args],text=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
    write(r.stdout.rstrip()); write(f'[exit {r.returncode}]')
    return r
user=['-u','tester','-e','XDG_RUNTIME_DIR=/run/user/1000','-e','NODE_NO_WARNINGS=1',container]
props=['-p','ManagedOOMMemoryPressure','-p','ManagedOOMMemoryPressureLimit','-p','ManagedOOMMemoryPressureDurationUSec']
watch="oomctl --no-pager | sed -n '/Memory Pressure Monitored CGroups:/,$p' | grep -E 'Monitored|Path:|Memory Pressure (Limit|Duration):'"
try:
    write('1. BEFORE INSTALL: system manager policy and live oomd watch')
    cmd('systemctl show user@1000.service (OOM policy)',[container,'systemctl','show','user@1000.service',*props])
    cmd('systemctl --user show -.slice (OOM policy)',[*user,'systemctl','--user','show',*props,'--','-.slice'])
    cmd('oomctl (monitored paths, limits and durations)',[container,'bash','-c',watch])
    frame().save(out/'initial.png'); time.sleep(2)
    with lock: lines.clear()
    write('2. INSTALL THE REAL T3 CLI, THEN OBSERVE THE WATCH')
    cmd('node /opt/source/apps/server/dist/bin.mjs service install --base-dir /home/tester/proof-data',user+['node','/opt/source/apps/server/dist/bin.mjs','service','install','--base-dir','/home/tester/proof-data'])
    # systemd-oomd consumes the manager notification asynchronously; allow one processing interval.
    write('Waiting 3 seconds for systemd-oomd notification processing...'); time.sleep(3)
    cmd('systemctl --user show -.slice (OOM policy)',[*user,'systemctl','--user','show',*props,'--','-.slice'])
    cmd('oomctl (monitored paths, limits and durations)',[container,'bash','-c',watch])
    cmd('runtime root-slice drop-ins',user+['bash','-c',"find /run/user/1000/systemd -path '*/inaccessible' -prune -o -path '*-.slice.d/*' -type f -exec cat '{}' ';'"])
    frame().save(out/'result.png'); time.sleep(3)
    with lock: lines.clear()
    write("3. DIAGNOSTIC: RUN THIS COMMIT'S RESTORE SCRIPT WITH sh -x")
    cmd('export RESTORE_OOMD_WATCH_SCRIPT from the unchanged source',[container,'bash','-c',"node --experimental-strip-types --input-type=module -e \"import { RESTORE_OOMD_WATCH_SCRIPT as s } from '/opt/source/apps/server/src/cloud/userManagerOom.ts'; process.stdout.write(s)\" > /tmp/restore.sh"])
    cmd('sh -x /tmp/restore.sh',user+['sh','-x','/tmp/restore.sh'])
    frame().save(out/'trace.png'); time.sleep(3)
finally:
    stop.set(); thread.join(); video.stdin.close(); video.wait()
    (out/'transcript.json').write_text(json.dumps(events,indent=2))
    (out/'transcript.txt').write_text(''.join(e['text']+'\n' for e in events))
