#!/usr/bin/env python3
"""Run real T3 CLIs against isolated synthetic PATH fixtures. No test framework."""
import os, sys, pathlib, subprocess, shutil, re, json, time
root=pathlib.Path(__file__).parent
stamp=str(time.time_ns()); run=root/('run-'+stamp); run.mkdir()
worktrees={'before':pathlib.Path(sys.argv[1]),'after':pathlib.Path(sys.argv[2])}
for side,wt in worktrees.items():
    case=run/side; case.mkdir(); home=case/'home'; home.mkdir()
    cli=wt/'apps/server/dist-exe/t3'
    started=time.monotonic()
    events=[]
    class Recording(list):
        def append(self, text):
            super().append(text)
            events.append([round(time.monotonic()-started,3),'o', ('\x1b[2J\x1b[H' if text.startswith('\n===') else '')+text+'\n'])
    logs=Recording()
    def clean(s):
        s=s.replace(str(case),'$CASE').replace(str(wt),'$CHECKOUT')
        s=re.sub(r'\x1b\[[0-9;]*m','',s)
        s=re.sub(r'userdata/triage/[^/\s]+','userdata/triage/<session>',s)
        return s
    def call(label,args,cwd,env,executable=None):
        logs.append('\n=== '+label+' ===\n$ '+clean(' '.join(args))+'\nPATH='+clean(env['PATH'])+'; cwd='+clean(str(cwd)))
        p=subprocess.run(args,cwd=cwd,env=env,executable=executable,text=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,timeout=60)
        logs.append(clean(p.stdout)+'\nexit='+str(p.returncode))
        time.sleep(1.5)
        return p
    env={'HOME':str(home),'PATH':':/usr/bin:/bin','T3CODE_DEV_SEED':'0','NO_COLOR':'1','TERM':'dumb'}
    agents=case/'agents'; agents.mkdir(); fake=agents/'codex'; fake.write_text('#!/bin/sh\nprintf "FAKE CODEX STARTED in %s\\n" "$PWD"\n'); fake.chmod(0o755)
    for i,path in enumerate(['.:/usr/bin:/bin',':/usr/bin:/bin',str(agents)+':/usr/bin:/bin']):
        call('Triage '+['relative PATH','empty PATH component','absolute PATH control'][i],[str(cli),'triage','--agent','codex','--base-dir',str(case/('triage-'+str(i)))],agents,{**env,'PATH':path})
    connect=case/'connect'; connect.mkdir(); shutil.copy2(cli,connect/'t3'); (connect/'node_modules').symlink_to(wt/'apps/server/node_modules')
    cf=connect/'cloudflared'; cf.write_text('#!/bin/sh\necho "cloudflared version 2026.11.1 (synthetic discovery fixture)"\n'); cf.chmod(0o755)
    p=call('T3 Connect status: cloudflared only in cwd; empty PATH component',[str(connect/'t3'),'connect','status','--base-dir',str(case/'connect-data'),'--log-level','error'],connect,env)
    match=re.search(r'Run `([^`]+)` to authorize',p.stdout)
    if match:
        hint=match.group(1); logs.append('Visible suggested command: '+clean(hint))
        # --help prevents real authorization; it still resolves the suggested executable.
        call('Paste suggested command from another directory (+ --help)', ['/bin/sh','-c',hint+' --help'],home,env)
    call('Cloudflared absolute PATH control', [str(connect/'t3'),'connect','status','--base-dir',str(case/'connect-control'),'--json','--log-level','error'],connect,{**env,'PATH':str(connect)+':/usr/bin:/bin'})
    call('CLI hint with relative dot PATH', [str(connect/'t3'),'connect','status','--base-dir',str(case/'connect-relative'),'--log-level','error'],connect,{**env,'PATH':'.:/usr/bin:/bin'})
    # A generated installer script starts the runtime by absolute name; findPosixLauncher must rediscover it.
    for kind in ['script','symlink']:
        directory=case/('launcher-'+kind); directory.mkdir(); data=directory/'data'; version=data/'runtime/versions/0.1.11'; version.mkdir(parents=True)
        shutil.copy2(cli,version/'t3'); (version/'node_modules').symlink_to(wt/'apps/server/node_modules'); launcher=directory/'t3'
        if kind=='script': launcher.write_text("#!/bin/sh\nexec '"+str(version/'t3')+"' \"$@\"\n"); launcher.chmod(0o755)
        else: launcher.symlink_to(version/'t3')
        # An uninstall plan without --yes is read-only in a non-TTY.
        call('Launcher discovery via '+kind+' and empty PATH component',['t3','uninstall','--base-dir',str(data)],directory,env,executable=str(launcher))
        # Use a cached synthetic target: no download, no running background service.
        target=data/'runtime/versions/0.1.12'; target.mkdir()
        (target/'.install-complete').write_text('0.1.12\n')
        staged=target/'t3'; staged.write_text('#!/bin/sh\ncase "$1" in\n__service-preflight) echo \'{"status":"ready","version":"0.1.12","launcherProtocol":4}\';;\n*) echo "SYNTHETIC TARGET 0.1.12";;\nesac\n'); staged.chmod(0o755)
        call('Update launcher via '+kind+' and empty PATH component',['t3','update','0.1.12','--base-dir',str(data)],directory,env,executable=str(launcher))
        logs.append('Launcher after update: '+clean(launcher.read_text() if kind=='script' or not launcher.is_symlink() else 'symlink -> '+str(launcher.readlink())))
    cast=root/(side+'.cast'); cast.write_text(json.dumps({'version':2,'width':150,'height':52,'timestamp':int(time.time()),'title':'Real CLI output — '+side,'env':{'TERM':'xterm-256color'}})+'\n'+'\n'.join(json.dumps(e) for e in events)+'\n')
    out=root/(side+'.txt'); out.write_text('\n'.join(logs)); print(out)
print('RUN='+str(run))
