import os, sys, pathlib, subprocess, shutil, datetime, hashlib
root = pathlib.Path(__file__).resolve().parent
run = root / ('run-' + datetime.datetime.now().strftime('%Y%m%d-%H%M%S'))
run.mkdir()
node = shutil.which('node')
binary = root / 'cloudflared'
binary.chmod(0o755)
print('Binary SHA256:', hashlib.sha256(binary.read_bytes()).hexdigest())
for side, checkout in [('before', sys.argv[1]), ('after', sys.argv[2])]:
    sha = subprocess.check_output(['git','rev-parse','HEAD'], cwd=checkout, text=True).strip()
    lines = [f'{side.upper()} | commit {sha}', 'Linux x86_64 | fresh data directory per case | real CLI', 'cloudflared 2026.10.4 official Linux amd64 release', 'Paths below replace the scratch root with <scratch>.']
    for name in ['bin-plain', 'bin space ', 'bin quote"', 'empty']:
        directory = run / name
        directory.mkdir(exist_ok=True)
        if name != 'empty': shutil.copy2(binary, directory / 'cloudflared')
        env = dict(os.environ, PATH=str(directory)+':/usr/bin:/bin', T3CODE_DEV_SEED='0', NO_COLOR='1')
        lines += ['', f'CASE: {name!r}', f'PATH={str(directory)!r}:/usr/bin:/bin', '$ bash -c \'command -v cloudflared && cloudflared version\'']
        native = subprocess.run(['/bin/bash','-c','command -v cloudflared && cloudflared version'], env=env, capture_output=True, text=True)
        lines += [(native.stdout+native.stderr).strip() or '(not found)', f'native exit: {native.returncode}', '$ node apps/server/src/bin.ts connect status --log-level none --base-dir <fresh>']
        result = subprocess.run([node,'apps/server/src/bin.ts','connect','status','--log-level','none','--base-dir', str(run / (side+'-data-'+str(len(lines))))],cwd=checkout,env=env,capture_output=True,text=True)
        lines += [(result.stdout+result.stderr).strip(), f'T3 exit: {result.returncode}']
    output='\n'.join(lines).replace(str(run), '<scratch>')+'\n'
    (run / (side+'.txt')).write_text(output)
    print(output)
print('RUN_DIRECTORY='+str(run))
