# Copyright (c) 2026 Peter Fors
# SPDX-License-Identifier: MIT

import json
import sys
from pathlib import Path
import cairo

BG = '0d1117'
TEXT = 'c9d1d9'
MUTED = '9198a1'
GRID = '21262d'
EDGE = '3d444d'
TEAL = '42ad9e'
BLUE = '669fc5'
SLATE = '778397'
RED = 'c76b6b'

data = json.loads(Path(sys.argv[1]).read_text())
output = Path(sys.argv[2]) if len(sys.argv)>2 else Path(__file__).parent
output.mkdir(exist_ok=True, parents=True)


def ink(cr, color, alpha=1):
    cr.set_source_rgba(*(int(color[i:i+2], 16)/255 for i in (0,2,4)), alpha)


def label(cr, x, y, text, size=16, align=0, color=TEXT, bold=False):
    cr.select_font_face('DejaVu Sans', cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_BOLD if bold else cairo.FONT_WEIGHT_NORMAL)
    cr.set_font_size(size)
    ink(cr, color)
    cr.move_to(x-align*cr.text_extents(text).x_advance,y)
    cr.show_text(text)


def line(cr, a, b, color=GRID, width=1, dash=()):
    ink(cr,color)
    cr.set_line_width(width)
    cr.set_dash(dash)
    cr.move_to(*a)
    cr.line_to(*b)
    cr.stroke()
    cr.set_dash(())


def dot(cr, x, y, color, radius=3, alpha=1):
    ink(cr,color,alpha)
    cr.arc(x,y,radius,0,6.28319)
    cr.fill()


def bar(cr, x, top, height, width, color):
    ink(cr,color)
    cr.rectangle(x-width/2,top,width,height)
    cr.fill()


def figure(name,title,subtitle,height=455):
    surf=cairo.SVGSurface(str(output/name),800,height)
    cr=cairo.Context(surf)
    ink(cr,BG)
    cr.paint()
    label(cr,30,41,title,27,bold=True)
    label(cr,30,69,subtitle,16,color=MUTED)
    return surf, cr


def legend(cr, entries):
    x=32
    y=110
    for color,text in entries:
        line(cr,(x,y-5),(x+21,y-5),color,3)
        label(cr,x+29,y,text,16)
        x+=cr.text_extents(text).x_advance+62


def axes(cr, xlim, ylim, yticks, xticks, xlabel, ylabel):
    left,right,top,bottom=76,770,150,349
    x=lambda n:left+(right-left)*(n-xlim[0])/(xlim[1]-xlim[0])
    y=lambda n:bottom-(bottom-top)*(n-ylim[0])/(ylim[1]-ylim[0])
    for n in yticks:
        line(cr,(left,y(n)),(right,y(n)),EDGE if n==ylim[0] else GRID)
        label(cr,left-10,y(n)+5,f'{n:g}',15,1,MUTED)
    for n in xticks:
        line(cr,(x(n),bottom),(x(n),bottom+5),EDGE)
        label(cr,x(n),bottom+24,f'{n:g}',15,.5,MUTED)
    label(cr,left,136,ylabel,16)
    label(cr,(left+right)/2,bottom+55,xlabel,16,.5)
    return x,y


def footer(cr, text):
    label(cr,30,439,text,14,color=MUTED)


def regimes():
    surface,cr=figure('regimes.svg','Two execution regimes with fixed buffers','Ryzen 9 9950X3D · CPU 9 · boost off · 4 KiB CJK reverse conversion')
    series=[('fast',TEAL,'Aligned fast'),('slow',RED,'Aligned slow'),('shifted',SLATE,'+128 B')]
    legend(cr,[(c,s) for _,c,s in series])
    x,y=axes(cr,(1550,2250),(0,700),range(0,701,175),range(1600,2201,150),'Core cycles per call','AL-token stall cycles per call')
    for key,color,_ in series:
        for cycles,al in data['ibs_cycles'][key]:
            dot(cr,x(cycles),y(al),color,3,.46)
    footer(cr,'Clang 23.1.5 / GCC 16.2.1 · Each point is one 131,072-call batch')
    surface.finish()


def load_tail():
    surface,cr=figure('ibs-tail.svg','Input loads that hit L1D','Ryzen 9 9950X3D · CPU 9 · boost off · Haswell AVX2 CJK loop')
    series=[('fast',TEAL,'Aligned fast'),('slow',RED,'Aligned slow'),('shifted',SLATE,'+128 B')]
    legend(cr,[(c,f'{s} ({len(data["ibs_hits"][k])})') for k,c,s in series])
    x,y=axes(cr,(16,96),(0,20),range(0,21,5),[20,35,50,65,80,95],'Tag-to-completion threshold (cycles)','Samples above threshold (%)')
    line(cr,(x(50),y(0)),(x(50),y(20)),EDGE,1.5,(4,4))
    for key,color,_ in series:
        values=[r['tag_complete'] for r in data['ibs_hits'][key]]
        thresholds=[16]+sorted(set(v for v in values if 16<v<=96))+[96]
        previous=sum(v>16 for v in values)*100/len(values)
        for lo,hi in zip(thresholds,thresholds[1:]):
            fraction=sum(v>hi for v in values)*100/len(values)
            line(cr,(x(lo),y(previous)),(x(hi),y(previous)),color,2.3)
            line(cr,(x(hi),y(previous)),(x(hi),y(fraction)),color,2.3)
            if hi in values:
                dot(cr,x(hi),y(fraction),color,2.5,1)
            previous=fraction
    footer(cr,'Clang 23.1.5 / GCC 16.2.1 · Tail shown from 16 cycles')
    surface.finish()


def drain():
    surface,cr=figure('store-drain.svg','Draining stores between calls','Ryzen 9 9950X3D · CPU 9 · boost off · 4 KiB CJK reverse conversion')
    legend(cr,[(TEAL,'Ordinary'),(BLUE,'MFENCE before each call')])
    x,y=axes(cr,(0,2),(0,2500),range(0,2501,500),[],'','Median core cycles per call')
    for index,(keys,title) in enumerate([(('slow_plain','slow_fenced'),'Aligned slow'),(('shifted','shifted_fence'),'+128 B control')]):
        center=x(index+.5)
        for shift,key,colour in zip((-61,61),keys,(TEAL,BLUE)):
            v=data['drain'][key]['cycles']
            bar(cr,center+shift,y(v),y(0)-y(v),93,colour)
            label(cr,center+shift,y(v)-8,f'{v:,.0f}',16,.5)
        label(cr,center,377,title,17,.5)
    footer(cr,'Clang 23.1.5 / GCC 16.2.1 · 30 matched slow pairs; 136 batches per control bar')
    surface.finish()


def idle():
    surface,cr=figure('idle-state.svg','What clears the slow regime','Ryzen 9 9950X3D · CPU 9 · boost off · trials starting slow')
    legend(cr,[(TEAL,'Fast on return'),(RED,'Slow on return'),(SLATE,'Ambiguous')])
    groups=[
        ('C1', ('C1',)),
        ('C2 or C3', ('C2 or C3',)),
        ('POLL', ('POLL',)),
        ('no recorded idle', ('No recorded', 'idle')),
        ('active spin', ('Active spin',)),
        ('busy helper', ('Busy helper',)),
    ]
    x,y=axes(cr,(0,len(groups)),(0,35),range(0,36,5),[],'','Trials')
    for index,(key,lines) in enumerate(groups):
        center=x(index+.5)
        for shift,state,color in zip((-33,0,33),('fast','slow','ambiguous'),(TEAL,RED,SLATE)):
            v=data['idle_groups'][key].get('slow/'+state,0)
            if v:
                bar(cr,center+shift,y(v),y(0)-y(v),26,color)
            label(cr,center+shift,y(v)-8,str(v),16,.5)
        for line_number,title in enumerate(lines):
            label(cr,center,377+20*line_number,title,17,.5)
    footer(cr,'Clang 23.1.5 / GCC 16.2.1 · States verified with cycles and AL-token stalls')
    surface.finish()


if __name__ == "__main__":
    regimes()
    load_tail()
    drain()
    idle()
