# Run while reproduce.py is waiting at READY FOR BROWSER.
# PROOF_RUN is the timestamped run directory printed/stored by that driver.
import os,json,sqlite3,subprocess
from pathlib import Path
run=Path(os.environ['PROOF_RUN'])
project=run/'synthetic-project'
project.mkdir(exist_ok=True)
subprocess.run(['git','init','-q',str(project)],check=True)
subprocess.run(['node','apps/server/src/bin.ts','project','add','--base-dir',str(run/'after-account/.t3'),'--title','Live account only',str(project)],cwd=os.environ['HEAD_CHECKOUT'],check=True)
for scope in ['userdata','dev']:
 directory=run/'after-account/.t3'/scope
 runtime=json.loads((directory/'server-runtime.json').read_text())
 con=sqlite3.connect('file:'+str(directory/'statev2.sqlite')+'?mode=ro',uri=True)
 print(scope,'PID',runtime['pid'],'port',runtime['port'],'projects',con.execute('select title from projection_projects').fetchall())
 con.close()
 descriptors=set()
 for fd in Path(f'/proc/{runtime["pid"]}/fd').iterdir():
  try:
   target=os.readlink(fd)
   if 'statev2.sqlite' in target: descriptors.add(target.replace(str(run/'after-account'),'$HOME'))
  except OSError: pass
 print('Open database descriptors:',sorted(descriptors))
