import os, sys, pathlib, subprocess, datetime
side, checkout = sys.argv[1:]
root = pathlib.Path(os.environ['EVIDENCE_DIR'])
run = root / (side + '-' + datetime.datetime.now().strftime('%Y%m%d%H%M%S'))
run.mkdir()
fixture = run / 'fixture'
fixture.mkdir()
env = dict(os.environ, T3CODE_HOME=str(root / (side+'-data')), T3CODE_DEV_SEED='0')
cli = ['node', checkout+'/apps/server/src/bin.ts']
lines = ['Real T3 Code CLI / Linux / isolated fresh server and synthetic data', 'Commit: '+subprocess.check_output(['git','-C',checkout,'rev-parse','HEAD'],text=True).strip(), '']
def command(args, cwd=fixture, display=None):
    p=subprocess.run(args,cwd=cwd,env=env,text=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
    out=p.stdout.replace(str(run),'<run>').replace(checkout,'<checkout>')
    lines.extend(['$ '+(display or ' '.join(args)),out.rstrip(),f'[exit {p.returncode}]',''])
    (run/'transcript.txt').write_text('\n'.join(lines))
    print('\n'.join(lines[-4:]),flush=True)
    return p
command(['git','init','-q','repo'])
repo=fixture/'repo'
command(['git','-c','user.name=Synthetic','-c','user.email=synthetic@example.invalid','commit','--allow-empty','-qm','initial'],repo)
command(['git','worktree','add','../feature','-b','feature'],repo)
command(['git','worktree','add','../live','-b','live'],repo)
for project in ['repo','feature']:
    command(cli+['project','add',str(fixture/project)],display='t3 project add '+project)
command(cli+['thread','start','--provider','codex','--model','gpt-6-luna',str(repo),'Reply with just: ok'],display='t3 thread start --provider codex --model gpt-6-luna repo "Reply with just: ok"')
command(cli+['thread','list','--json'],fixture/'live','cd live; t3 thread list --json  # both registered checkouts live')
(fixture/'feature').rename(fixture/'moved-feature')
(fixture/'feature').mkdir()
lines.extend(['$ mv feature moved-feature; mkdir feature',''])
command(['git','worktree','list','--porcelain'],repo)
command(cli+['thread','list','--json'],fixture/'live','cd live; t3 thread list --json  # feature is now prunable')
command(cli+['thread','list','--json','--project','../repo'],fixture/'live','cd live; t3 thread list --json --project ../repo  # explicit control')
print('TRANSCRIPT',run/'transcript.txt')
