import os, pathlib, subprocess, sqlite3, datetime, re, json, sys
root=pathlib.Path(__file__).parent
run=root/datetime.datetime.now().strftime('run-%Y%m%d-%H%M%S');run.mkdir()
results={}
for side,checkout in [('before',sys.argv[1]),('after',sys.argv[2])]:
 d=run/side;d.mkdir(); home=d/'home';cwd=d/'cwd';cwd.mkdir();(home/'app').mkdir(parents=True);(home/'shared').mkdir()
 env=dict(os.environ,HOME=str(home),T3CODE_DEV_SEED='0',NO_COLOR='1');env.pop('T3CODE_HOME',None)
 lines=[f'{side.upper()} — real T3 CLI on Linux',f'Commit: '+subprocess.check_output(['git','rev-parse','HEAD'],cwd=checkout,text=True).strip(),'Environment: HOME=<fixture>/home; cwd=<fixture>/cwd (empty)',"Created HOME/app and HOME/shared; fresh state for each command.",'']
 codes=[]
 for name,args in [('track',['--track','~/shared']),('control',[])]:
  state=d/('state-'+name)
  cmd=['node',checkout+'/apps/server/src/bin.ts','project','add','~/app',*args,'--base-dir',str(state)]
  p=subprocess.run(cmd,cwd=cwd,env=env,text=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
  out=p.stdout.replace(str(d),'<fixture>').replace(checkout,'<checkout>')
  lines += ["$ t3 project add '~/app' "+("--track '~/shared' " if args else '')+f'--base-dir <fresh-{name}-state>',out.strip(),f'Exit code: {p.returncode}','']
  codes.append(p.returncode)
  dbs=list(state.rglob('statev2.sqlite'))
  if name=='track' and dbs:
   con=sqlite3.connect('file:'+str(dbs[0])+'?mode=ro',uri=True)
   for table, in con.execute("select name from sqlite_master where type='table'"):
    if 'project' in table:
     cols=[r[1] for r in con.execute(f'pragma table_info("{table}")')]
     if 'tracked_folders_json' in cols or any('track' in c for c in cols):
      rows=con.execute(f'SELECT * FROM "{table}"').fetchall()
      lines += ['Persisted '+table+':',json.dumps([dict(zip(cols,r)) for r in rows],indent=2).replace(str(d),'<fixture>'),'']
   con.close()
 text='\n'.join(lines);(run/(side+'.txt')).write_text(text);results[side]=codes
print(run);print(results)
