import os,sys,pathlib,subprocess,time,json,re
side,root=sys.argv[1:]
r=pathlib.Path(root); cache=pathlib.Path(os.environ.get('EVIDENCE_CACHE',str(r/'cache')))/'t3code/compile-cache'
def measure(label):
    files=[p for p in cache.rglob('*') if p.is_file()]
    usage=subprocess.check_output(['du','-sk',str(cache)],text=True).split()[0] if cache.exists() else '0'
    dirs=sorted(p.name for p in cache.iterdir() if p.is_dir()) if cache.exists() else []
    print(f'{label}: {len(files)} files; {usage} KiB allocated; folders: {", ".join(dirs) or "(none)"}',flush=True)
print(f'AppImage CLI compile-cache — {side.upper()}',flush=True)
print('Linux x86_64 | packaged Electron AppImage | stopped server',flush=True)
print('1920x1080 display | dark terminal | fresh synthetic app home',flush=True)
print('APPIMAGE, NODE_COMPILE_CACHE, NODE_DISABLE_COMPILE_CACHE unset',flush=True)
print('Seed: server/preserve.txt + v0-evidence/legacy.txt (same on both sides)',flush=True)
for name in ['server/preserve.txt','v0-evidence/legacy.txt']:
    p=cache/name;p.parent.mkdir(parents=True,exist_ok=True);p.write_text('synthetic evidence sentinel\n')
measure('Initial')
env=os.environ.copy()
for k in ['APPIMAGE','NODE_COMPILE_CACHE','NODE_DISABLE_COMPILE_CACHE','ELECTRON_RUN_AS_NODE']:env.pop(k,None)
env.update(HOME=str(r/'home'),T3CODE_HOME=str(r/'app'),XDG_CACHE_HOME=str(cache.parent.parent),XDG_CONFIG_HOME=str(r/'config'),XDG_DATA_HOME=str(r/'data'))
for i in range(1,4):
    print(f'\n$ t3 thread show evidence-stopped-thread --json --messages 2  [call {i}]',flush=True)
    p=subprocess.run([str(r/'app/bin/t3'),'thread','show','evidence-stopped-thread','--json','--messages','2'],env=env,text=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
    # Keep paths and connection credentials out of the public transcript.
    output=p.stdout.replace(str(r),'<isolated-home>')
    output=re.sub(r'/tmp/[^\s\']+', '<temporary-path>', output)
    for line in output.splitlines():
        if 'token' not in line.lower() and 'ws://' not in line and 'http' not in line:print(line,flush=True)
    print(f'Exit status: {p.returncode}',flush=True)
    measure(f'After call {i}')
    time.sleep(2)
print('\nPreserved server sentinel:',(cache/'server/preserve.txt').read_text().strip(),flush=True)
print('Legacy engine sentinel exists:',(cache/'v0-evidence/legacy.txt').exists(),flush=True)
print('\nCapture complete.',flush=True)
time.sleep(5)
