#!/usr/bin/env python3
"""Run built standalone t3 install, then Bash command lookup, in six fresh sandboxes.
Usage: python3 driver.py HEAD_CHECKOUT BASE_CHECKOUT OUTPUT_DIRECTORY
Transcripts replace synthetic sandbox paths with $DEMO for public sharing.
"""
import os, pathlib, subprocess, sys, datetime, shutil
head, base, out = map(pathlib.Path, sys.argv[1:])
out = out / datetime.datetime.now().strftime('%Y%m%d-%H%M%S')
out.mkdir(parents=True)
for side, checkout in [('before',base),('after',head)]:
    sha = subprocess.check_output(['git','rev-parse','HEAD'],cwd=checkout,text=True).strip()
    lines = [f'{side.upper()} | {sha[:10]}', 'Linux x86_64 | Bash | standalone t3 v0.1.10', 'Fresh synthetic HOME per case; $DEMO = case sandbox', 'Real command output; paths normalized for sharing.','']
    for case, kind, onpath in [('0','none',True),('1','directory',True),('2','file',True),('3','file',False),('3b','directory',False),('4','executable',True)]:
        root = out / side / ('case-'+case)
        runtime = root / 'home/.t3/runtime/versions/0.1.10'
        runtime.mkdir(parents=True)
        exe = runtime / 't3'
        shutil.copy2(checkout / 'apps/server/dist-exe/t3',exe)
        (runtime / 'node_modules').symlink_to(checkout / 'apps/server/node_modules')
        other, bindir = root / 'other', root / 'bin'
        other.mkdir(); bindir.mkdir()
        candidate = other / 't3'
        if kind == 'directory': candidate.mkdir()
        elif kind != 'none':
            candidate.write_text('#!/bin/sh\necho fake-t3\n')
            candidate.chmod(0o755 if kind == 'executable' else 0o644)
        path = ':'.join(map(str,([other] if kind != 'none' else []) + ([bindir] if onpath else []))) + ':/usr/bin:/bin'
        env = {'HOME':str(root/'home'),'PATH':path,'SHELL':'/bin/bash','T3CODE_INSTALL_BIN_DIR':str(bindir),'NO_COLOR':'1','TERM':'dumb','T3CODE_DEV_SEED':'0'}
        def run(args):
            p=subprocess.run(args,env=env,cwd=root,text=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
            return p.stdout.strip(),p.returncode
        install, code = run([str(exe),'install'])
        shell, shellcode = run(['/bin/bash','--noprofile','--norc','-c','t3 --version'])
        lines += [f'CASE {case}: earlier t3 = {kind}; installed bin on PATH = {onpath}', '$ runtime/t3 install', install, f'[exit {code}]', '$ bash --noprofile --norc -c "t3 --version"', shell, f'[exit {shellcode}]','']
        lines = [line.replace(str(root),'$DEMO') for line in lines]
    (out/(side+'.txt')).write_text('\n'.join(lines))
print(out)
