import asyncio, subprocess, pathlib, json, os, sys, time, datetime, re, signal
from PIL import Image, ImageDraw, ImageFont
ROOT=pathlib.Path(__file__).parent
checkout=pathlib.Path(sys.argv[1]).resolve(); side=sys.argv[2]
out=ROOT/(side+'-'+datetime.datetime.now().strftime('%H%M%S'));out.mkdir()
processes=[]; lines=[]; start=time.monotonic(); recording=True
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',18)
video=subprocess.Popen(['ffmpeg','-hide_banner','-loglevel','error','-y','-f','rawvideo','-pixel_format','rgb24','-video_size','1440x900','-framerate','1','-i','-','-c:v','libx264','-preset','ultrafast','-crf','24','-pix_fmt','yuv420p',str(out/'recording.mp4')],stdin=subprocess.PIPE)
def clean(s):
    s=s.replace(__import__('socket').gethostname(),'Remote server').replace(str(out),'[run-data]').replace(str(checkout),'[checkout]')
    return re.sub(r'\x1b\[[0-9;]*[mK]','',s)
def emit(s):
    s=clean(s)
    for line in s.splitlines():
        line=f'{time.monotonic()-start:6.1f}s  {line}'; lines.append(line);print(line,flush=True)
    (out/'transcript.txt').write_text('\n'.join(lines)+'\n')
def frame():
    im=Image.new('RGB',(1440,900),'#10151e');d=ImageDraw.Draw(im)
    d.text((24,18),f'T3 Code workflow cancellation | {side} | '+sha[:10],font=font,fill='#73cfff')
    d.text((24,50),'Real servers + OpenCode 2.4.3 / GPT 6.1 Sol | fresh synthetic data | CLI output',font=font,fill='#a8b5c5')
    wrapped=[]
    import textwrap
    for line in lines:
        wrapped.extend(textwrap.wrap(line, width=120,replace_whitespace=False) or [''])
    for i,line in enumerate(wrapped[-33:]): d.text((24,100+i*23),line,font=font,fill='#e4eaf2')
    return im
async def recorder():
    while recording:
        video.stdin.write(frame().tobytes());await asyncio.sleep(1)
async def cli(who,*args,secret=False,check=True):
    cmd=['node',str(checkout/'apps/server/src/bin.ts'),*args,'--base-dir',str(out/who)]
    p=await asyncio.create_subprocess_exec(*cmd,cwd=checkout,stdout=asyncio.subprocess.PIPE,stderr=asyncio.subprocess.PIPE,env={**os.environ,'T3CODE_DEV_SEED':'0'})
    raw,err=await p.communicate();s=raw.decode();e=err.decode()
    if not secret:
        emit('$ t3 '+ ' '.join(args));emit(s+e)
    if check and p.returncode:raise RuntimeError(clean(s+e))
    return s
async def waitfor(fn,limit=90):
    deadline=time.monotonic()+limit
    while time.monotonic()<deadline:
        value=fn()
        if value:return value
        await asyncio.sleep(1)
    raise RuntimeError('Timed out waiting for starting state')
connections=set(); enabled=True
async def proxy(reader,writer):
    if not enabled:writer.close();return
    try:
        r,w=await asyncio.open_connection('127.0.0.1',portB);connections.update([writer,w])
        async def pump(a,b):
            while data:=await a.read(65536):b.write(data);await b.drain()
        tasks=[asyncio.create_task(pump(reader,w)),asyncio.create_task(pump(r,writer))]
        await asyncio.wait(tasks,return_when=asyncio.FIRST_COMPLETED)
        for t in tasks:t.cancel()
        w.close();writer.close();connections.discard(writer);connections.discard(w)
    except Exception:writer.close()
def freeport():
    import socket
    s=socket.socket();s.bind(('127.0.0.1',0));p=s.getsockname()[1];s.close();return p
sha=subprocess.check_output(['git','rev-parse','HEAD'],cwd=checkout,text=True).strip()
portA=freeport();portB=freeport();portP=freeport()
async def main():
    global enabled,recording
    rec=asyncio.create_task(recorder());srv=await asyncio.start_server(proxy,'127.0.0.1',portP)
    try:
        emit('Starting two isolated real T3 servers; transport proxy forwards bytes unchanged.')
        for who,port in [('A',portA),('B',portB)]:
            data=out/who;(data/'userdata').mkdir(parents=True)
            (data/'userdata/settings.json').write_text(json.dumps({'linkedEnvironmentsEnabled':True,'workflowsEnabled':True,'providerInstances':{'opencode':{'driver':'opencode','enabled':True,'config':{'enabled':True}}}}))
            log=open(out/(who+'-private-server.log'),'w')
            p=subprocess.Popen(['node','apps/server/src/bin.ts','serve','--port',str(port),'--host','127.0.0.1','--base-dir',str(data)],cwd=checkout,stdout=log,stderr=log,env={**os.environ,'T3CODE_DEV_SEED':'0'})
            processes.append(p)
            await waitfor(lambda:(data/'userdata/server-runtime.json').exists())
        token=json.loads(await cli('B','auth','pairing','create','--json',secret=True))
        (out/'pair-private.json').write_text(json.dumps(token))
        emit('Pairing credential issued (kept out of captures).')
        # Determine pairing payload without logging secrets.
        code=token.get('credential') or token.get('token') or token.get('pairingToken') or token.get('pairingCode')
        if not code:raise RuntimeError('Pairing shape: '+str(list(token)))
        await cli('A','environment','link',f'http://127.0.0.1:{portP}','--pairing-code',code,'--access','full-access',secret=True)
        linked=json.loads(await cli('A','environment','list','--json'))
        envId=linked[0]['environmentId']
        project=out/'writer';project.mkdir();await cli('B','project','add',str(project),'--title','Remote writer')
        wf=out/'A/workflows';wf.mkdir(exist_ok=True)
        brief='Run this exact foreground shell command now with a timeout of at least 660000ms: for i in $(seq 1 600); do date -u +%FT%TZ >> ticks.log; sleep 1; done . Do not background it, do not shorten it, do not read or change any other files. Wait for this command to finish.'
        definition='const {workflow,agent}=T3; export default workflow("remote-writer",{version:1,payload:Schema.Struct({})},Effect.fn(function*(){yield* agent("writer",'+json.dumps({'environment':envId,'project':str(project),'model':{'instanceId':'opencode','model':'openai/gpt-6.1-sol'},'runtimeMode':'full-access','brief':brief})+');}));'
        (wf/'remote-writer.ts').write_text(definition)
        await asyncio.sleep(4)
        run=json.loads(await cli('A','workflow','start','remote-writer','--key','run1','--json'))
        runId=run['run']['runId'];tick=project/'ticks.log'
        await waitfor(lambda:tick.exists() and len(tick.read_text().splitlines())>=5,180)
        run=json.loads(await cli('A','workflow','show',runId,'--json'))
        (out/'run-initial.json').write_text(json.dumps(run,indent=2))
        thread=run['steps'][0].get('threadId')
        if not thread:
            # Stored agent turn is the step value while it is running.
            val=run['steps'][0].get('value') or run['steps'][0].get('result')
            if isinstance(val,str):val=json.loads(val)
            thread=val.get('threadId') if isinstance(val,dict) else None
        if not thread:raise RuntimeError('Could not locate recorded thread')
        await cli('B','thread','show',thread,'--messages','0')
        emit('ticks.log lines before outage: '+str(len(tick.read_text().splitlines())))
        enabled=False
        for w in list(connections):w.close()
        emit('NETWORK CUT: proxy refuses connections; remote server and agent stay running.')
        await cli('A','environment','list')
        await cli('A','workflow','cancel',runId)
        emit('ticks.log lines after cancel returns: '+str(len(tick.read_text().splitlines())))
        enabled=True;emit('NETWORK RESTORED. Observe remote turn across workflow sweeps (15 s).')
        await cli('A','environment','list')
        readings=[]
        for n in range(1,7):
            await asyncio.sleep(15)
            count=len(tick.read_text().splitlines());emit(f'RECONNECT +{n*15}s: ticks.log lines={count}; last tick={tick.read_text().splitlines()[-1]}')
            status=await cli('B','thread','show',thread,'--messages','0')
            readings.append({'seconds':n*15,'ticks':count,'thread':status})
        await cli('A','workflow','show',runId)
        (out/'observations.json').write_text(json.dumps({'sha':sha,'side':side,'readings':readings},indent=2))
        frame().save(out/'final.png')
        emit('Observation complete. Stopping only the servers started by this driver.')
    finally:
        srv.close();await srv.wait_closed()
        for w in list(connections):w.close()
        for p in processes:p.terminate()
        for p in processes:
            try:await asyncio.to_thread(p.wait,20)
            except subprocess.TimeoutExpired:p.kill();p.wait()
        recording=False;await rec;video.stdin.close();video.wait()
        print('ARTIFACTS',out,flush=True)
asyncio.run(main())
