from PIL import Image,ImageDraw,ImageFont
import pathlib,json,subprocess
root=pathlib.Path(__file__).parent
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',19)
small=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',16)
for side in ['before','after']:
    out=pathlib.Path((root/(side+'-output.txt')).read_text()); rows=[json.loads(l) for l in (out/'receiver.jsonl').read_text().splitlines()]
    def frame(t):
        im=Image.new('RGB',(1500,1050),'#101820'); d=ImageDraw.Draw(im)
        def line(y,s,color='#e5edf5',f=font):d.text((30,y),s,font=f,fill=color)
        line(22,'OTLP RECEIVER | '+side.upper()+' | real t3 serve', '#7ac8ff')
        line(55,'Commit '+rows[0]['commit'],f=small)
        line(85,'Linux / Node / fresh isolated home / default Info level / default 10s exports',f=small)
        line(115,'Receiver: logs = 503; metrics = 200, except t=35..60s = 503',f=small)
        line(150,f'Elapsed: {t:5.1f}s | Recorded HTTP requests and decoded OTLP counter points', '#f1cf7d')
        visible=[r for r in rows if r['seconds']<=t and 'endpoint'in r]
        y=195
        for r in visible[-23:]:
            counters=[]
            for m in r['failureCounter']:
                for p in m['sum']['dataPoints']:
                    a={a['key']:a['value'].get('stringValue') for a in p['attributes']}
                    counters.append(f"{a.get('signal')}/{a.get('reason')}={p.get('asDouble',p.get('asInt'))}")
            s=f"{r['seconds']:6.2f}s {r['endpoint']:12} HTTP {r['status']}"
            if r['endpoint']=='/v1/metrics':s+=' | '+(', '.join(counters) if counters else 'failure counter ABSENT')
            line(y,s,'#ffa89c' if r['status']==503 else '#9ee4be',small);y+=29
        line(900,'Metric: t3_otlp_export_attempt_failures_total', '#7ac8ff')
        line(935,'Displayed values come directly from the receiver payloads; no test or mocked exporter.',f=small)
        line(970,'Receiver transcript replay at 5x; timestamped JSONL and driver accompany this capture.',f=small)
        return im
    frame(139).save(root/(side+'.png'))
    p=subprocess.Popen(['ffmpeg','-y','-f','rawvideo','-pix_fmt','rgb24','-s','1500x1050','-r','5','-i','-','-an','-c:v','libx264','-pix_fmt','yuv420p','-crf','23',str(root/(side+'.mp4'))],stdin=subprocess.PIPE,stderr=subprocess.DEVNULL)
    for t in range(141):p.stdin.write(frame(t).tobytes())
    p.stdin.close();p.wait()
    (root/(side+'-receiver.jsonl')).write_text((out/'receiver.jsonl').read_text())
