#!/usr/bin/env python3
"""Capture real T3/Pi behavior. Usage: prove-pi-resume.py base|head WORKTREE PORT
Requires Pi configured for anthropic/claude-haiku-4-5-20251001, Pillow, ffmpeg.
Place pi-wrapper.py and trace.ts beside this driver. Output is fresh for each run.
The video renders the timestamped terminal stream, as an asciicast player would.
"""
import os,sys,json,time,subprocess,datetime,urllib.request
from pathlib import Path
from PIL import Image,ImageDraw,ImageFont
side=sys.argv[1];wt=Path(sys.argv[2]).resolve();port=int(sys.argv[3]);root=Path(__file__).parent
sha=subprocess.check_output(['git','rev-parse','HEAD'],cwd=wt,text=True).strip()
run=root/(side+'-full-'+datetime.datetime.now().strftime('%H%M%S'));run.mkdir()
home=run/'t3-home';(home/'userdata').mkdir(parents=True)
project=run/'pi-resume-demo';project.mkdir();(project/'README.md').write_text('Synthetic Pi resume evidence.\n')
trace=run/'pi-private.jsonl';trace.touch()
config={'providerInstances':{'pi':{'driver':'pi','enabled':True,'environment':[{'name':'PI_TRACE','value':str(trace),'sensitive':False}],'config':{'enabled':True,'binaryPath':str(root/'pi-wrapper.py'),'launchArgs':'-e '+str(root/'trace.ts')}}}}
(home/'userdata/settings.json').write_text(json.dumps(config))
for args in [['init','-q',str(project)],['-C',str(project),'add','.'],['-C',str(project),'-c','user.name=Evidence','-c','user.email=evidence@example.invalid','commit','-qm','Initial']]:subprocess.run(['git',*args],check=True)
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',19)
rows=[];timeline=[];start=time.monotonic();saved=None;others={};offset=0;active=None;exts=set();pending={};server=None;serverlog=None;replies=[];third=0

def output(s):
 rows.append(s);timeline.append([round(time.monotonic()-start,3),'o',s+'\r\n']);print(s,flush=True)
def session(s):
 global saved
 if saved is None:saved=s
 if s==saved:return '<saved-session.jsonl>'
 if s not in others:others[s]='<new-session-%d.jsonl>'%(len(others)+1)
 return others[s]
def extension(e):
 output('EXT '+e['event']+(' reason='+e['reason'] if 'reason' in e else '')+(' session='+session(e['session']) if 'session' in e else '')+(' target='+session(e['target']) if 'target' in e else ''))
def drain():
 global offset,active
 lines=trace.read_text().splitlines()
 for line in lines[offset:]:
  e=json.loads(line);pid=e['pid'];ev=e['event']
  if e['source']=='wrapper':
   if ev=='launch' and '--extension' in e['args']:
    active=pid;a=e['args'];output('Pi launch: --mode rpc'+(' --session '+session(a[a.index('--session')+1]) if '--session' in a else ' [no --session]')+' -e trace.ts --extension t3-mcp.ts')
   elif pid==active and ev=='rpc':
    c=e['command'];s='RPC > '+c['type']
    for k in ['sessionPath','modelId','message','name']:
     if k in c:s+=' '+(session(c[k]) if k=='sessionPath' else json.dumps(c[k]))
    output(s)
   elif pid==active and ev=='response' and e['data']['command']=='get_state':
    d=e['data'].get('data',{});output('RPC < get_state: session='+session(d.get('sessionFile','none'))+', messages='+str(d.get('messageCount')))
  else:
   if pid not in exts:
    pending.setdefault(pid,[]).append(e)
    if 'pi-resume-demo' in e.get('session','') or 'pi-resume-demo' in e.get('target',''):
     exts.add(pid)
     for item in pending.pop(pid):extension(item)
   else:extension(e)
 offset=len(lines)
def cli(args,label):
 output('$ t3 '+label)
 for attempt in range(40):
  p=subprocess.Popen(['node','apps/server/src/bin.ts',*args,'--base-dir',str(home)],cwd=wt,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True)
  while p.poll() is None:drain();time.sleep(.1)
  drain();out=p.stdout.read()
  if not p.returncode:return out
  if 'is not advertised by provider pi' not in out:raise RuntimeError('CLI failed: '+out)
  if attempt==0:output('Waiting for Pi model discovery to finish before creating the thread...')
  time.sleep(.5)
 raise RuntimeError('Pi model discovery did not finish')

def boot(n):
 global server,serverlog,offset
 output('$ Start T3 server'+(' again, with the same home' if n else ' with a fresh isolated home'))
 serverlog=open(run/('server-%d-private.log'%n),'w')
 server=subprocess.Popen(['node','apps/server/src/bin.ts','serve','--port',str(port),'--base-dir',str(home),'--no-browser'],cwd=wt,env={**os.environ,'T3CODE_DEV_SEED':'0'},stdout=serverlog,stderr=subprocess.STDOUT)
 for _ in range(150):
  try:urllib.request.urlopen('http://127.0.0.1:%d/.well-known/t3/environment'%port,timeout=1).read();break
  except Exception:time.sleep(.1)
 else:raise RuntimeError('server startup failed')
 # Discovery processes have no attached session and are excluded by the trace filter.
 drain();output('T3 server ready.')
def stop():
 global server
 if server:
  server.terminate()
  try:server.wait(timeout=20)
  except subprocess.TimeoutExpired:server.kill();server.wait()
  server=None;serverlog.close()

def frame(lines):
 im=Image.new('RGB',(1440,1000),'#111318');d=ImageDraw.Draw(im)
 for n,line in enumerate(lines[-40:]):d.text((24,18+n*24),line,font=font,fill=('#80e8ad' if line.startswith('EXT') else '#e5e7eb'))
 return im

output(('BEFORE' if side=='base' else 'AFTER')+' | '+sha[:10])
output('Linux | real T3 server + CLI | Pi 1.5.2 | Claude Haiku 4.5')
output('Synthetic git project; no copied database; paths replaced by stable labels.')
try:
 for n,word in enumerate(['ONE','TWO','THREE']):
  if n:stop();output('');output('$ Stop T3 server; retain the same state')
  if n==2:third=len(rows)
  boot(n)
  if n==0:
   cli(['project','add',str(project),'--title','Pi resume proof'],'project add <synthetic-git-project>');output('Project added through the real app CLI.')
   args=['thread','start',str(project),'Reply with just the word '+word,'--provider','pi','--model','anthropic/claude-haiku-4-5-20251001','--title','Pi resume proof','--wait','--json']
  else:args=['thread','send',thread,'Reply with just the word '+word,'--wait','--json']
  out=cli(args,'thread '+('start <project>' if n==0 else 'send <same-thread>')+' "Reply with just the word '+word+'" --wait')
  data=json.loads(out.splitlines()[0]);thread=data['threadId'];replies.append({'status':data['status'],'reply':data['reply']});output('CLI < status='+data['status']+' reply='+str(data['reply']))
  if data['status']!='completed':raise RuntimeError('Turn did not complete')
 output('Trace ends before normal server shutdown.');time.sleep(1)
finally:stop()
(run/'transcript.txt').write_text('\n'.join(rows)+'\n')
(run/'outcomes.json').write_text(json.dumps({'side':side,'sha':sha,'replies':replies},indent=2))
with open(run/'terminal.cast','w') as f:
 f.write(json.dumps({'version':2,'width':112,'height':44,'timestamp':int(time.time()),'title':side+' real Pi resume'})+'\n')
 for event in timeline:f.write(json.dumps(event)+'\n')
frame([rows[0],rows[1],'Second restart of the same real thread (THREE):','',*rows[third:]]).save(run/'trace.png')
ff=subprocess.Popen(['ffmpeg','-y','-loglevel','error','-f','rawvideo','-pixel_format','rgb24','-video_size','1440x1000','-framerate','10','-i','-','-c:v','libx264','-preset','fast','-crf','20','-pix_fmt','yuv420p',str(run/'terminal.mp4')],stdin=subprocess.PIPE)
for tick in range(int((timeline[-1][0]+3)*10)):
 ff.stdin.write(frame([e[2].rstrip('\r\n') for e in timeline if e[0]<=tick/10]).tobytes())
ff.stdin.close();assert ff.wait()==0
print('ARTIFACTS '+str(run),flush=True)
