import sys,subprocess,pathlib,re,time,json
root=pathlib.Path(__file__).parent
side,checkout,state,log,sha=sys.argv[1:]
def clean(s):
 s=s.replace(str(root/state),'<isolated-data>')
 s=re.sub(r'"cloudUserId": "[^"]+"','"cloudUserId": "<test-account>"',s)
 return s
out=[]
def emit(s):
 s=clean(s);out.append(s);print(s,flush=True)
print('\033[?25l',end='',flush=True)
emit(f'{side.upper()} | commit {sha}\nLinux CLI from source | fresh isolated data | T3 Connect test stage\n')
lines=(root/log).read_text().splitlines()
emit('Server runtime after restart without CLI secrets:')
for line in lines:
 if 'Relay client process started' in line or 'Relay client tunnel connection registered' in line or 'T3 Connect is reachable from other devices.' in line:
  emit(line)
time.sleep(1)
for flags in [[],['--json']]:
 emit('\n$ t3 connect status '+(' '.join(flags)+' ' if flags else '')+'--base-dir <isolated-data>')
 p=subprocess.run(['node','apps/server/src/bin.ts','connect','status',*flags,'--base-dir',str(root/state)],cwd=checkout,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True)
 emit(p.stdout.rstrip())
 if p.returncode:raise SystemExit(p.returncode)
(root/f'{side}-transcript.txt').write_text('\n'.join(out)+'\n')
(root/f'{side}-capture-ready').touch()
time.sleep(20)
