import os, sys, subprocess, pathlib, datetime, json
root = pathlib.Path(__file__).parent
checkout = pathlib.Path(sys.argv[1]).resolve()
side = sys.argv[2]
run = root / (side + '-' + datetime.datetime.now().strftime('%Y%m%dT%H%M%S'))
run.mkdir()
sha = subprocess.check_output(['git','rev-parse','HEAD'],cwd=checkout,text=True).strip()
lines = ['REAL T3 CLI / SQLite capture', 'Side: '+side+'    Commit: '+sha, 'Environment: Linux x86_64; Node '+subprocess.check_output(['node','--version'],text=True).strip(), 'Fresh directories and database for each run; no server or copied state.', 'JSON strings below use ASCII escapes to expose lone UTF-16 surrogates.', '']
records=[]
for number, names in enumerate([['a'*127+'🚀'], ['b'*126+'🚀', ' '*127+'🚀']],1):
    cwd=run/('run'+str(number)); cwd.mkdir(); (cwd/'app').mkdir()
    for name in names: (cwd/name).mkdir()
    args=['node',str(checkout/'apps/server/dist/bin.mjs'),'project','add','app']
    for name in names: args+=['--track',name]
    args+=['--base-dir','state']
    env={**os.environ,'T3CODE_DEV_SEED':'0','NO_COLOR':'1'}
    result=subprocess.run(args,cwd=cwd,env=env,text=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,timeout=120)
    output=result.stdout.replace(str(cwd),'<fresh-directory>')
    lines+=['RUN '+str(number), '$ t3 project add app '+ ' '.join('--track '+json.dumps(n,ensure_ascii=True) for n in names)+' --base-dir state',output.strip(), 'CLI exit: '+str(result.returncode)]
    if result.returncode: raise RuntimeError(output)
    raw=subprocess.check_output(['sqlite3','state/userdata/statev2.sqlite','select tracked_folders_json from projection_projects'],cwd=cwd,text=True).strip()
    folders=json.loads(raw)
    lines+=['$ sqlite3 state/userdata/statev2.sqlite "select tracked_folders_json from projection_projects"']
    safe=[{**f,'path':'<fresh-directory>/'+pathlib.Path(f['path']).name} for f in folders]
    lines += [json.dumps(safe,ensure_ascii=True)]
    for f in folders:
        name=f['name']; encoded=name.encode('utf-16-le','surrogatepass'); units=[int.from_bytes(encoded[i:i+2],'little') for i in range(0,len(encoded),2)]
        well=not any(0xD800<=ord(c)<=0xDFFF for c in name)
        record={'input':pathlib.Path(f['path']).name,'storedName':name,'utf16Units':len(units),'lastUnit':hex(units[-1]) if units else None,'wellFormed':well}
        records.append(record)
        lines+=['Stored name: '+json.dumps(name,ensure_ascii=True),'UTF-16 units: '+str(len(units))+' | last unit: '+record['lastUnit']+' | well formed: '+str(well).lower(),'']
lines+=['SUMMARY']
for r in records:
    inp=r['input']; label='127 letters + rocket' if inp.startswith('a') else ('126 letters + rocket' if inp.startswith('b') else '127 spaces + rocket')
    lines += [label+': '+str(r['utf16Units'])+' units, well formed='+str(r['wellFormed']).lower()]
(run/'capture.txt').write_text('\n'.join(lines)+'\n')
(run/'observations.json').write_text(json.dumps({'sha':sha,'side':side,'records':records},ensure_ascii=True,indent=2)+'\n')
print(run)
print('\n'.join(lines[-4:]))
