import os,sys,subprocess,time,pathlib,json,signal
root=pathlib.Path(sys.argv[1]); out=pathlib.Path(sys.argv[2]);out.mkdir(parents=True) # Use a fresh output directory for each run.
env=os.environ.copy(); env.update(T3CODE_HOME=str(out/'home'),T3CODE_DEV_SEED='0',XDG_CONFIG_HOME=str(out/'config'))
procs=[]
def start(args,name,**kw):
 p=subprocess.Popen(args,cwd=root,env=env,stdout=open(out/(name+'.log'),'w'),stderr=subprocess.STDOUT,**kw);procs.append(p);return p
try:
 owner=start(['node','apps/server/dist/bin.mjs','serve','--host','127.0.0.1','--port','3790','--base-dir',str(out/'home')],'owner')
 runtime=out/'home/userdata/server-runtime.json'
 for _ in range(120):
  if runtime.exists(): break
  if owner.poll()!=None: raise RuntimeError('owner exited')
  time.sleep(.5)
 print('OWNER',runtime.read_text(),flush=True)
 start(['node','apps/server/dist/bin.mjs','status','--base-dir',str(out/'home')],'status').wait(timeout=30)
 rec=start(['ffmpeg','-y','-f','x11grab','-video_size','1920x1080','-framerate','10','-i',env['DISPLAY'],'-c:v','libx264','-preset','ultrafast','-pix_fmt','yuv420p',str(out/'startup.mp4')],'record')
 electron=start([str(root/'apps/desktop/node_modules/electron/dist/electron'),'--no-sandbox','--disable-gpu','apps/desktop/dist-electron/main.cjs'],'electron')
 time.sleep(12)
 subprocess.run(['import','-window','root',str(out/'still1.png')],check=True)
 time.sleep(.5)
 subprocess.run(['import','-window','root',str(out/'still2.png')],check=True)
 print('STABLE', (out/'still1.png').read_bytes()==(out/'still2.png').read_bytes(),flush=True)
 rec.send_signal(signal.SIGINT);rec.wait(timeout=10)
 subprocess.run(['xdotool','key','Return'])
 try: electron.wait(timeout=10)
 except subprocess.TimeoutExpired: pass
finally:
 for p in reversed(procs):
  if p.poll() is None:
   p.terminate()
   try:p.wait(timeout=10)
   except subprocess.TimeoutExpired:p.kill();p.wait()
