import os,sys,pathlib,subprocess,sqlite3,datetime,json
# Usage: python3 reproduce.py BASE_CHECKOUT HEAD_CHECKOUT OUTPUT_ROOT
out=pathlib.Path(sys.argv[3])/datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ');out.mkdir(parents=True)
for side,checkout in zip(('before','after'),sys.argv[1:3]):
 root=out/side
 for name in ('cwd/ subdir','ws1','ws2','ws3'): (root/name).mkdir(parents=True,exist_ok=True)
 lines=[f'{side.upper()} — real T3 CLI, Linux, Node '+subprocess.check_output(['node','--version'],text=True).strip(), 'Commit: '+subprocess.check_output(['git','-C',checkout,'rev-parse','HEAD'],text=True).strip(), 'Fresh isolated state; paths below are normalized to <run> and <checkout>.','']
 for i,value in enumerate(('', '   ', ' subdir'),1):
  args=['node',str(pathlib.Path(checkout)/'apps/server/src/bin.ts'),'project','add',f'../ws{i}','--track',value,'--base-dir','../state']
  p=subprocess.run(args,cwd=root/'cwd',env={**os.environ,'T3CODE_DEV_SEED':'0'},capture_output=True,text=True,timeout=120)
  lines += [f'$ t3 project add ../ws{i} --track {json.dumps(value)} --base-dir ../state',f'Exit: {p.returncode}',p.stdout+p.stderr]
  dbs=list((root/'state').rglob('statev2.sqlite'))
  if dbs:
   db=sqlite3.connect(f'file:{dbs[0]}?mode=ro',uri=True)
   tables=db.execute("select name from sqlite_master where type='table' and sql like '%tracked_folders_json%'").fetchall()
   for (table,) in tables:
    rows=db.execute(f'SELECT * FROM "{table}"').fetchall();cols=[d[0] for d in db.execute(f'SELECT * FROM "{table}"').description]
    for row in rows:
     obj=dict(zip(cols,row));lines.append('DB project: '+json.dumps({k:v for k,v in obj.items() if k in ('workspace_root','title','tracked_folders_json','path')}))
   db.close()
  else: lines.append('DB: not created (validation stopped before state initialization).')
  lines.append('')
 text='\n'.join(lines).replace(str(root),'<run>').replace(checkout,'<checkout>')
 (out/f'{side}.txt').write_text(text)
 print(text)
print('ARTIFACT_DIR='+str(out))
