import os,sys,pathlib,shutil,json,time,re,pexpect
ROOT=pathlib.Path(__file__).parent
out=ROOT/time.strftime('run-%Y%m%d-%H%M%S'); out.mkdir()
for side,checkout in [('before',sys.argv[1]),('after',sys.argv[2])]:
 repo=pathlib.Path(checkout); version=json.loads((repo/'apps/server/package.json').read_text())['version']
 for flag in ['--token-only','--token-only=true','--json']:
  name=side+'-'+flag[2:].replace('=','-'); home=out/name; home.mkdir()
  package=home/'.npm/_npx/fixture/node_modules/t3'; (package/'bin').mkdir(parents=True)
  shutil.copy(repo/'scripts/npm-launcher/t3.mjs',package/'bin/t3.mjs'); (package/'package.json').write_text(json.dumps({'name':'t3','version':version}))
  runtime=home/'.t3/runtime/versions'/version; runtime.mkdir(parents=True)
  shutil.copy(repo/'apps/server/dist-exe/t3-linux-x64',runtime/'t3'); (runtime/'.install-complete').write_text(version+'\n')
  (runtime/'node_modules').symlink_to(repo/'apps/server/node_modules',target_is_directory=True)
  env={k:v for k,v in os.environ.items() if not k.startswith(('T3','npm_','XDG_')) and k not in ['CI','SUDO_USER']}
  env.update(HOME=str(home),PATH='/usr/bin:/bin',TERM='xterm-256color',T3CODE_DEV_SEED='0')
  node=os.environ['EVIDENCE_NODE']
  child=pexpect.spawn(node,[str(package/'bin/t3.mjs'),'auth','session','issue',flag],env=env,encoding='utf-8',dimensions=(30,110),timeout=60)
  events=[]; raw=''; start=time.monotonic(); answered=False
  while True:
   try: chunk=child.read_nonblocking(4096,timeout=.1)
   except pexpect.TIMEOUT:
    if time.monotonic()-start>60: raise RuntimeError('CLI timeout')
    continue
   except pexpect.EOF: break
   raw+=chunk; events.append([time.monotonic()-start,chunk])
   if 'Install the t3 command?' in raw and not answered:
    time.sleep(1.5); child.send('n\r'); answered=True
  child.close()
  # Credentials never leave this isolated run. Redact JWTs in every public artifact.
  def redact(s): return re.sub(r'[A-Za-z0-9_-]{30,}\.[A-Za-z0-9_-]{30,}','[BEARER TOKEN REDACTED]',s)
  events=[[t,redact(s)] for t,s in events]
  # Re-redact across chunk boundaries as well.
  clean=redact(raw)
  (out/(name+'.txt')).write_text(clean+'\nExit '+str(child.exitstatus)+'\n')
  # Full stream redaction then retain observed timing for terminal playback.
  token=re.search(r'[A-Za-z0-9_-]{30,}\.[A-Za-z0-9_-]{30,}',raw)
  if token:
   secret=token.group(); joined=''; safe=[]
   # A token is emitted in one write in these runs; verify no fragment remains.
   for t,s in events: safe.append([t,s])
   if secret in ''.join(s for _,s in safe): raise RuntimeError('redaction failed')
  (out/(name+'.json')).write_text(json.dumps({'side':side,'flag':flag,'exit':child.exitstatus,'prompt':answered,'events':events}))
  print(name,'exit',child.exitstatus,'prompt',answered,'token',bool(token),flush=True)
print(out)
