import pathlib,json
from PIL import Image,ImageDraw,ImageFont
root=pathlib.Path(__file__).parent
for side,run,sha in [('before','before-run-2','aadf2c577c4c08482d7f771df96872469ba414f5'),('after','after-run','8af03a5d2888b35df9d96d57845847ca2782dcab')]:
 p=root/run/'home/userdata/logs/server-child.log'
 rows=[json.loads(x) for x in p.read_text().splitlines()]
 sessions=[]; current=None
 for r in rows:
  a=r['annotations']
  if a.get('phase')=='START':
   a['details']='backend launch (working directory redacted)'
   current={'timestamp':r['timestamp'],'prefix':None,'replacements':0,'end':None};sessions.append(current)
  if 'text' in a:
   if current['prefix'] is None:current['prefix']=a['text'][:32]
   current['replacements']+=a['text'].count('\ufffd')
  if a.get('phase')=='END':current['end']=a['details']
 (root/(side+'-server-child.jsonl')).write_text('\n'.join(json.dumps(r,ensure_ascii=False) for r in rows)+'\n')
 summary={'side':side,'commit':sha,'environment':'Linux Electron 44.10.1; Xvfb 1920x1080; fresh app home; default light theme','fixtureBytes':1048704,'sourceBytes125to133':'79 79 c3 a9 63 68 65 63 0a','sessions':sessions}
 (root/(side+'-summary.json')).write_text(json.dumps(summary,ensure_ascii=False,indent=2))
 im=Image.new('RGB',(1500,650),'#111827');d=ImageDraw.Draw(im)
 font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',23)
 lines=[side.upper()+': persisted desktop server-child.log',sha,'Linux Electron | fresh app home | 1 MiB + 128 bytes stderr','Source at offset 127: échec (valid UTF-8 c3 a9)', '', 'First retained stderr text: '+repr(sessions[0]['prefix']), '', 'Failure sessions captured: '+str(len(sessions))]
 for i,s in enumerate(sessions[:7]):lines.append('Session %d: prefix=%s  U+FFFD=%d  %s'%(i+1,repr(s['prefix'][:6]),s['replacements'],s['end']))
 for i,l in enumerate(lines):d.text((35,25+i*38),l,font=font,fill='#f9fafb')
 im.save(root/(side+'-log.png'))
 print(side,json.dumps(sessions,ensure_ascii=False))
