import subprocess,json,time,sys,textwrap,threading
from pathlib import Path
from PIL import Image,ImageDraw,ImageFont
ROOT=Path('/tmp/factory-issue-40477-evidence-2')
side,checkout,thread,sha=sys.argv[1:]
out=ROOT/(side+'-'+str(int(time.time()))); out.mkdir()
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',20)
lines=[]; events=[]; start=time.monotonic(); lock=threading.Lock(); finished=False
video=subprocess.Popen(['ffmpeg','-y','-loglevel','error','-f','rawvideo','-pixel_format','rgb24','-video_size','1600x1000','-framerate','2','-i','-','-c:v','libx264','-preset','fast','-crf','23','-pix_fmt','yuv420p',str(out/'recording.mp4')],stdin=subprocess.PIPE)
def frame():
 im=Image.new('RGB',(1600,1000),'#10151d'); d=ImageDraw.Draw(im)
 d.text((35,25),f'{side.upper()} | {sha[:10]} | Real T3 server / Claude Haiku 5.5',font=font,fill='#a8d4ff')
 d.text((35,55),'CLI transcript • fresh isolated database • 1600 × 1000 • dark',font=font,fill='#aeb9c9')
 with lock: visible=lines[-34:]
 for n,line in enumerate(visible): d.text((35,105+n*25),line,font=font,fill='#e5eaf1')
 return im
def record():
 while not finished:
  video.stdin.write(frame().tobytes()); time.sleep(.5)
t=threading.Thread(target=record);t.start()
def emit(s):
 s=s.replace(str(ROOT/'project'),'<scratch-project>').replace(checkout,'<checkout>')
 with lock:
  for line in s.splitlines(): lines.extend(textwrap.wrap(line,124,replace_whitespace=False) or [''])
 events.append({'elapsed':round(time.monotonic()-start,2),'text':s})
 print(s,flush=True)
def cli(args):
 p=subprocess.run(['node','apps/server/src/bin.ts',*args,'--base-dir','.t3'],cwd=checkout,text=True,capture_output=True,timeout=90)
 raw=p.stdout+p.stderr
 (out/('command-'+str(len(events))+'.txt')).write_text(raw.replace(str(ROOT/'project'),'<scratch-project>').replace(checkout,'<checkout>'))
 if p.returncode: emit(raw); raise RuntimeError('CLI failed')
 return json.loads(p.stdout)
def show(label):
 data=cli(['thread','show','--json',thread]); th=data['thread']
 emit(label+': '+json.dumps({'status':th['status'],'activeRun':th['activeRunId'] is not None,'backgroundTasks':th['pendingBackgroundTasks'],'messages':data['messages'][-2:],'error':data['error']},ensure_ascii=False).replace(thread,'<thread>'))
 return data
def settled():
 for _ in range(40):
  data=cli(['thread','show','--json',thread])
  if data['thread']['activeRunId'] is None:return data
  time.sleep(1)
 raise RuntimeError('turn did not settle')
try:
 emit('$ t3 thread show --json <thread>')
 initial=show('Before repository change')
 assert initial['thread']['pendingBackgroundTasks']
 assert any(m['role']=='assistant' and m['text']=='started' for m in initial['messages'])
 emit('$ write t3.json: {"ignoreRepositories":["vendor/foo"]}')
 Path('/tmp/factory-issue-40477-evidence-2/project/t3.json').write_text('{"ignoreRepositories":["vendor/foo"]}\n')
 for i in range(2):
  emit('$ t3 thread send <thread> "Reply with the word ok."')
  cli(['thread','send','--json',thread,'Reply with the word ok.'])
  settled(); show('Send '+str(i+1)+' result')
 emit('$ remove t3.json (restore original repository list)')
 Path('/tmp/factory-issue-40477-evidence-2/project/t3.json').unlink()
 emit('$ t3 thread send <thread> "Reply with the word back."')
 cli(['thread','send','--json',thread,'Reply with the word back.'])
 settled(); show('Restored-list control')
 emit('Capture complete. No composer model or settings changed.')
 frame().save(out/'result.png')
 (out/'events.json').write_text(json.dumps(events,indent=2))
 time.sleep(2)
finally:
 finished=True;t.join();video.stdin.close();video.wait()
 print('OUTPUT_DIRECTORY='+str(out),flush=True)
