# Usage: python3 driver.py BASE_WORKTREE HEAD_WORKTREE (after vp i and vp run build:bundle in each apps/server)
import os, subprocess, pathlib, time, json, re, signal, urllib.request, shlex, datetime, sys, shutil
ROOT=pathlib.Path(__file__).parent
RUN=ROOT/datetime.datetime.now().strftime('run-%Y%m%d-%H%M%S'); RUN.mkdir()
NODE=shutil.which('node')
ansi=re.compile(r'\x1b\[[0-?]*[ -/]*[@-~]')
for side,suffix,sha in [('base','-base','44ebb2fe57'),('head','','839a9ee868')]:
    work=pathlib.Path(sys.argv[1] if side=='base' else sys.argv[2]).resolve()
    launcher=ROOT/side/'t3'
    launcher.parent.mkdir(exist_ok=True)
    launcher.write_text('#!/bin/sh\nexec '+shlex.quote(NODE)+' '+shlex.quote(str(work/'apps/server/dist/bin.mjs'))+' \"$@\"\n')
    launcher.chmod(0o755)
    events=[]; started=time.monotonic()
    def clean(s):
        s=ansi.sub('',s)
        for path,alias in [(str(ROOT/side),'/evidence'),(str(work),'/checkout'),(str(ROOT),'/scratch')]: s=s.replace(path,alias)
        s=re.sub(r'pid \d+','pid <server>',s)
        s=re.sub(r'(?i)(token=|Token: )[A-Z2-9]+',r'\1[REDACTED]',s)
        s=re.sub(r'Pairing with .*? \(http', 'Pairing with <synthetic environment> (http',s)
        s=re.sub(r'App link: .*','App link: [REDACTED]',s)
        return s
    def emit(s):
        s=clean(s); print(s,flush=True); events.append([round(time.monotonic()-started,3),'o',s+'\n'])
    def command(args,env,title):
        emit('$ '+title)
        r=subprocess.run(args,cwd=work,env=env,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True,timeout=60)
        output=ansi.sub('',r.stdout)
        # QR encodes a credential; keep only human-readable pairing summary.
        shown='\n'.join(l for l in output.splitlines() if not any('\u2580'<=c<='\u259f' for c in l))
        emit(shown.strip()+'\nexit: '+str(r.returncode))
        return r,output
    emit(f'{side.upper()} | commit {sha}\nLinux x86_64 | packaged CLI from linked worktree\nFresh synthetic database | loopback :17643 | no browser\nPaths aliased; credentials redacted. Same driver on both commits.')
    for selection in ['environment','flag']:
        home=ROOT/side/('run-home-'+selection+'-'+RUN.name)
        env=os.environ.copy(); env.pop('T3CODE_HOME',None)
        env.update(T3CODE_DEV_SEED='0',T3CODE_CLI_PATH=str(launcher),NO_COLOR='1',TERM='dumb')
        args=[str(launcher)]
        if selection=='environment': env['T3CODE_HOME']=str(home)
        else: args += ['--base-dir',str(home)]
        emit('\n=== '+('T3CODE_HOME' if selection=='environment' else '--base-dir')+' selects isolated home ===')
        log=open(RUN/(side+'-'+selection+'-server-private.log'),'w')
        server=subprocess.Popen(args+['--no-browser','--port','17643'],cwd=work,env=env,stdout=log,stderr=subprocess.STDOUT)
        try:
            deadline=time.monotonic()+60
            while time.monotonic()<deadline:
                if server.poll() is not None: raise RuntimeError('Server exited: '+str(server.returncode))
                if (home/'userdata/server-runtime.json').exists():
                    try:
                        urllib.request.urlopen('http://127.0.0.1:17643/.well-known/t3/environment',timeout=1); break
                    except Exception: pass
                time.sleep(.2)
            else: raise RuntimeError('Server not ready')
            emit('Background server started; live environment descriptor responds HTTP 200.')
            guidance=None
            for sub in [[],['start']]:
                cmd=[str(launcher)]+sub
                if selection=='flag': cmd+=['--base-dir',str(home)]
                title=('T3CODE_HOME=/evidence/'+home.name+' ' if selection=='environment' else '')+'t3'+(' start' if sub else '')+(' --base-dir /evidence/'+home.name if selection=='flag' else '')
                r,out=command(cmd,env,title)
                m=re.search(r'To open it, run `([^`]+)`',out)
                if m: guidance=m.group(1)
            pairenv=env.copy(); pairenv.pop('T3CODE_HOME',None)
            emit('From linked worktree, unset T3CODE_HOME; follow printed command if present.')
            if guidance:
                r,out=command(shlex.split(guidance),pairenv,clean(guidance))
                m=re.search(r'Pairing URL: (\S+)',out)
                if m:
                    url=m.group(1); token=url.split('#token=')[1]
                    req=urllib.request.Request('http://127.0.0.1:17643/api/auth/browser-session',data=json.dumps({'credential':token}).encode(),headers={'Content-Type':'application/json'},method='POST')
                    with urllib.request.urlopen(req) as response:
                        emit('Use printed URL credential at original server: HTTP '+str(response.status)+'; session cookie issued: '+str(bool(response.headers.get('Set-Cookie'))))
            else:
                emit('No pairing command is printed. Try bare t3 pair from this linked worktree:')
                command([str(launcher),'pair'],pairenv,'t3 pair')
        finally:
            server.terminate()
            try: server.wait(timeout=20)
            except subprocess.TimeoutExpired: server.kill(); server.wait()
            log.close()
            emit('Background server stopped.')
    (RUN/(side+'.txt')).write_text('\n'.join(e[2] for e in events))
    with open(RUN/(side+'.cast'),'w') as f:
        f.write(json.dumps({'version':2,'width':112,'height':32,'timestamp':0,'env':{'TERM':'dumb'},'title':side+' CLI proof'})+'\n')
        for event in events: f.write(json.dumps(event)+'\n')
print('OUTPUT_DIRECTORY='+str(RUN))
