import pathlib,json,textwrap,subprocess
from PIL import Image,ImageDraw,ImageFont
root=pathlib.Path(__file__).parent
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',22)
for side in ['before','after']:
 run=sorted(p for p in root.glob(side+'-*') if p.is_dir())[-1]; events=json.loads((run/'transcript.json').read_text())
 lines=['EXTERNAL MCP / REAL SERVER RESPONSE CAPTURE',side.upper()+'  '+events[0]['response']['commit'],'Linux x64 | Node server | loopback HTTP | fresh database','T3CODE_DEV_SEED=0 | public OAuth client: ChatGPT | Full access','Pairing approval + PKCE S256 | protocol 2025-06-18','Secrets and local paths omitted. No mocked services.','']
 frames=[]
 for event in events[1:]:
  name=event['step'];r=event['response'];lines.append('> '+name)
  if name.startswith('OAuth'):v='scope: '+r['scope']
  elif name=='initialize':v='result: T3 Code / protocol '+r['result']['protocolVersion']
  elif name=='tools/list':v=str(r['count'])+' tools; '+', '.join(r['issueTools'])
  elif name=='t3_project_create':v='isError: false; registered GitHub-backed checkout'
  else:
   result=r['result'];v='isError: '+str(result.get('isError',False)).lower()+'; '
   if result.get('isError'):v+=result['content'][0]['text']
   else:
    payload=result.get('structuredContent') or json.loads(result['content'][0]['text'])
    if name=='list_issues':v+='returned '+str(len(payload['issues']))+' real GitHub issues; errors: '+json.dumps(payload['errors'])
    elif name=='read_issue':v+=payload['displayKey']+' '+payload['title']
  lines+=textwrap.wrap(v,width=109,initial_indent='  ',subsequent_indent='  ')+['']
  img=Image.new('RGB',(1600,1100),'#10151d');d=ImageDraw.Draw(img)
  for i,line in enumerate(lines):d.text((32,25+i*31),line,font=font,fill='#e4eaf2')
  frame=root/(side+'-frame-'+str(len(frames))+'.png');img.save(frame);frames.append(frame)
 frames[-1].replace(root/(side+'.png'))
 frames[-1]=root/(side+'.png')
 (root/(side+'.txt')).write_text('\n'.join(lines)+'\n')
 (root/(side+'-responses.json')).write_text(json.dumps(events,indent=2))
 concat=root/(side+'-frames.txt');concat.write_text(''.join("file '"+str(f)+"'\nduration 1.5\n" for f in frames)+"file '"+str(frames[-1])+"'\n")
 subprocess.run(['ffmpeg','-v','error','-y','-f','concat','-safe','0','-i',str(concat),'-vf','fps=10','-c:v','libx264','-pix_fmt','yuv420p',str(root/(side+'.mp4'))],check=True)
