import os, sys, subprocess as sp, time, json, pathlib, threading, re
from PIL import Image, ImageDraw, ImageFont
ROOT=pathlib.Path(__file__).parent
run=ROOT/time.strftime('run-%Y%m%d-%H%M%S'); run.mkdir()
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',19)
def command(args,cwd=None):
 return sp.check_output(args,cwd=cwd,stderr=sp.STDOUT,text=True).strip()
def git(cwd,*args): return command(['git',*args],cwd)
for side,checkout,sha,port in [('before',sys.argv[1],sys.argv[3],18431),('after',sys.argv[2],sys.argv[4],18432)]:
 d=run/side; d.mkdir(); upstream=d/'upstream.git'; author=d/'author'; repo=d/'checkout'; home=d/'home'; (home/'userdata').mkdir(parents=True)
 git(d,'init','--bare','--initial-branch=main',str(upstream)); git(d,'clone',str(upstream),str(author))
 git(author,'config','user.name','Evidence'); git(author,'config','user.email','evidence@example.com')
 (author/'sample.txt').write_text('first commit\n'); git(author,'add','.'); git(author,'commit','-m','Initial'); git(author,'push','-u','origin','main')
 git(d,'clone',str(upstream),str(repo)); initial=git(repo,'rev-parse','--short','HEAD')
 wrapper=d/'slow-upload-pack.sh'; fetchlog=d/'fetch.log'
 wrapper.write_text('#!/bin/sh\necho "fetch connection started" >> "'+str(fetchlog)+'"\nsleep 8\necho "8-second delay complete" >> "'+str(fetchlog)+'"\nexec git-upload-pack "$@"\n'); wrapper.chmod(0o755)
 git(repo,'config','remote.origin.uploadpack',str(wrapper))
 (author/'sample.txt').write_text('second commit\n'); git(author,'add','.'); git(author,'commit','-m','Upstream update'); git(author,'push','origin','main'); target=git(author,'rev-parse','--short','HEAD')
 (home/'userdata'/'settings.json').write_text(json.dumps({'defaultAutoPull':True}))
 raw=open(d/'server-raw.log','w'); env=os.environ.copy(); env.update(T3CODE_DEV_SEED='0',T3CODE_LOG_LEVEL='Debug'); env.pop('T3CODE_HOME',None)
 p=sp.Popen(['node',str(pathlib.Path(checkout)/'apps/server/src/bin.ts'),'--base-dir',str(home),'--port',str(port),'--host','127.0.0.1','--no-browser','--auto-bootstrap-project-from-cwd',str(repo)],cwd=checkout,env=env,stdout=raw,stderr=sp.STDOUT)
 start=time.monotonic(); events=[]; seen=set(); frames=[]
 try:
  for second in range(66):
   deadline=start+second; time.sleep(max(0,deadline-time.monotonic()))
   logs=(d/'server-raw.log').read_text(); fetch=fetchlog.read_text().splitlines() if fetchlog.exists() else []
   for i,line in enumerate(fetch):
    key='fetch'+str(i)
    if key not in seen: events.append(f'{second:02}s  '+line); seen.add(key)
   for phrase in ['Background Git fetch is still running; using the last fetched references.','Automatic project pull completed','Automatic project pull failed','Skipped automatic project pull']:
    if phrase in logs and phrase not in seen: events.append(f'{second:02}s  '+phrase); seen.add(phrase)
   head=git(repo,'rev-parse','--short','HEAD'); remote=git(repo,'rev-parse','--short','origin/main'); status=git(repo,'status','--short','--branch')
   lines=[f'{side.upper()} | T3 real server | {sha[:10]}','Linux / Node CLI | fresh isolated state | no clients connected','Automatic pull enabled | clean main tracking origin/main','Each fetch connection delays 8 seconds, then succeeds','',f'Elapsed: {second:02}s     Server alive: {p.poll() is None}',f'Initial HEAD: {initial}    Upstream target: {target}',f'Checkout HEAD: {head}   origin/main: {remote}',f'git status: {status}','','Observed server / transport events:',*events[-11:]]
   img=Image.new('RGB',(1280,720),'#101723'); draw=ImageDraw.Draw(img)
   for i,line in enumerate(lines): draw.text((30,24+i*28),line,font=font,fill='#e0e6ee')
   frame=d/f'frame-{second:03}.png'; img.save(frame); frames.append(frame)
   (d/'transcript.txt').write_text('\n'.join(lines)+'\n')
  print(side, '\n'.join(lines),flush=True)
 finally:
  p.terminate()
  try:p.wait(timeout=12)
  except sp.TimeoutExpired:p.kill();p.wait()
  raw.close()
 sp.run(['ffmpeg','-loglevel','error','-y','-framerate','1','-i',str(d/'frame-%03d.png'),'-c:v','libx264','-pix_fmt','yuv420p',str(d/f'{side}.mp4')],check=True)
 (d/f'{side}.png').write_bytes(frames[-1].read_bytes())
print('OUTPUT',run,flush=True)
