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

import json
import math
from pathlib import Path
from statistics import median, quantiles

import cairo

ROOT = Path(__file__).resolve().parent
FIGURE_WIDTH = 800
FIGURE_HEIGHT = 500
PLOT_BOX = (73, 151, 695, 229)


def rgb(hex_value):
	return tuple(int(hex_value[i:i+2], 16) / 255 for i in (0, 2, 4))


BACKGROUND = rgb('0d1117')
TEXT = rgb('c9d1d9')
SECONDARY = rgb('9198a1')
GRID = rgb('21262d')
BORDER = rgb('3d444d')
TEAL = rgb('42ad9e')
BLUE = rgb('669fc5')
SLATE = rgb('778397')


def label(cr, x, y, value, size=16, align=0, bold=False, colour=TEXT):
	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)
	cr.set_source_rgb(*colour)
	cr.move_to(x - align * cr.text_extents(value).x_advance, y)
	cr.show_text(value)


def line(cr, x1, y1, x2, y2, colour, width=1):
	cr.set_source_rgb(*colour)
	cr.set_line_width(width)
	cr.move_to(x1, y1)
	cr.line_to(x2, y2)
	cr.stroke()


def legend(cr, y, entries):
	x = 32
	for colour, value in entries:
		line(cr, x, y - 4, x + 23, y - 4, colour, 2)
		label(cr, x + 31, y, value)
		x += cr.text_extents(value).x_advance + 59


def frame(surface, title, subtitle):
	cr = cairo.Context(surface)
	cr.set_source_rgb(*BACKGROUND)
	cr.paint()
	label(cr, 32, 41, title, 27, bold=True)
	label(cr, 32, 68, subtitle, colour=SECONDARY)
	return cr


def panel(cr, box, title, xlabel, x_ticks, y_ticks, series, refs=()):
	left, top, width, height = box
	xpos = lambda x: left + width * (x - x_ticks[0]) / (x_ticks[-1] - x_ticks[0])
	ypos = lambda y: top + height * (y_ticks[-1] - y) / (y_ticks[-1] - y_ticks[0])
	label(cr, left, top - 16, title, 19, bold=True)
	for y in y_ticks:
		line(cr, left, ypos(y), left + width, ypos(y), BORDER if y == y_ticks[0] else GRID)
		label(cr, left - 9, ypos(y) + 4, f'{y:g}', 15, align=1, colour=SECONDARY)
	for x in x_ticks:
		line(cr, xpos(x), top + height, xpos(x), top + height + 4, BORDER)
		label(cr, xpos(x), top + height + 24, f'{x:g}', 15, align=.5, colour=SECONDARY)
	label(cr, left + width / 2, top + height + 47, xlabel, 17, align=.5)
	for x in refs:
		cr.set_dash((4, 4))
		line(cr, xpos(x), top, xpos(x), top + height, SECONDARY)
		cr.set_dash(())
	for colour, points in series:
		cr.new_path()
		cr.set_source_rgb(*colour)
		cr.set_line_width(2)
		for (x, _, _), (y, _, _) in points:
			cr.line_to(xpos(x), ypos(y))
		cr.stroke()
		for (x, xl, xh), (y, yl, yh) in points:
			if xl != xh:
				line(cr, xpos(xl), ypos(y), xpos(xh), ypos(y), colour)
			if yl != yh:
				line(cr, xpos(x), ypos(yl), xpos(x), ypos(yh), colour)
			cr.arc(xpos(x), ypos(y), 3.2, 0, 2 * math.pi)
			cr.fill()


def fixed(value):
	return value, value, value


def distribution(values):
	low, _, high = quantiles(values, n=4, method='inclusive')
	return median(values), low, high


def raw(name):
	return json.loads((ROOT / f'{name}-raw.json').read_text())


def draw_figure(filename, subtitle, entries, panel_data, notes, refs=()):
	with cairo.SVGSurface(str(ROOT / filename), FIGURE_WIDTH, FIGURE_HEIGHT) as surface:
		title, *axes = panel_data
		cr = frame(surface, title, subtitle)
		legend(cr, 100, entries)
		panel(cr, PLOT_BOX, *axes, refs)
		for row, note in enumerate(notes):
			label(cr, 32, 457 + 21 * row, note, 14, colour=SECONDARY)


def capacity():
	entries = ((TEAL, 'Delayed source'), (BLUE, 'Ready source'))
	for arch, model, reference in (('zen5', 'Ryzen 9 9950X3D (CPU 9)', 88), ('zen4', 'Ryzen 9 7950X (CPU 7)', 96)):
		samples = [row for row in raw(arch)['samples'] if row['variant'] != 'chains']
		depths = sorted({row['input'] for row in samples})
		queues = ('r1af:u',) if arch == 'zen5' else ('r1af:u', 'r2af:u', 'r4af:u', 'r8af:u')
		metrics = (lambda group: max(group[event] for event in queues), lambda group: group['cycles:u'])
		cpu = 'Zen 5' if arch == 'zen5' else 'Zen 4'
		stall_file = 'scheduler-capacity.svg' if arch == 'zen5' else 'zen4-scheduler-stalls.svg'
		stall_title = 'AL-token stalls' if arch == 'zen5' else 'integer scheduler stalls'
		stall_axis = 'AL stall cycles per iteration' if arch == 'zen5' else 'Largest queue stall count per iteration (cycles)'
		plots = ((stall_file, f'{cpu} {stall_title}', stall_axis, (0, 200, 400, 600)), (f'{arch}-iteration-time.svg', f'{cpu} iteration time', 'Core cycles per iteration', (0, 500, 1000, 1500, 2000)))
		subtitle = f'{model}  |  boost enabled  |  64 B loop alignment'
		limit = '88 AL scheduler entries' if arch == 'zen5' else '96 aggregate integer scheduler entries'
		notes = ('GNU binutils 2.47  |  median of three interleaved rounds', f'Dashed line marks {limit}.')
		for (filename, title, axis, y_ticks), metric in zip(plots, metrics):
			series = []
			for (colour, _), variant in zip(entries, ('dependent', 'ready')):
				points = []
				for n in depths:
					values = [metric(row['groups'][-1]) / row['iterations'] for row in samples if row['input'] == n and row['variant'] == variant]
					points.append((fixed(n), fixed(median(values))))
				series.append((colour, points))
			data = (title, axis, 'LEAs switched to the delayed source', (0, 32, 64, 80, 88, 96, 112, 128), y_ticks, series)
			draw_figure(filename, subtitle, entries, data, notes, (reference,))

def tail_jump(name):
	data = raw(name)
	guest = data['metadata']['guest_instructions']
	entries = ((TEAL, '32 LEAs/tail'), (BLUE, '28 LEAs/tail'), (SLATE, '24 LEAs/tail'))
	absolute, relative = [], []
	for (colour, _), width in zip(entries, (32, 28, 24)):
		rows = [row for row in data['samples'] if row['width'] == width]
		ref = {row['round']: row['counts']['cycles:u'] for row in rows if row['depth'] == 0}
		points, changes = [], []
		for depth in sorted({row['depth'] for row in rows}):
			case = [row for row in rows if row['depth'] == depth]
			points.append((distribution([row['counts']['r1af:u'] / guest for row in case]), distribution([row['counts']['cycles:u'] / guest for row in case])))
			changes.append((fixed(depth), distribution([100 * (row['counts']['cycles:u'] / ref[row['round']] - 1) for row in case])))
		absolute.append((colour, points))
		relative.append((colour, changes))
	x_min = math.floor(min(x[1] for _, points in absolute for x, _ in points))
	x_max = math.ceil(max(x[2] for _, points in absolute for x, _ in points))
	y_min = math.floor(min(y[1] for _, points in absolute for _, y in points))
	y_max = math.ceil(max(y[2] for _, points in absolute for _, y in points))
	r_min = 5 * math.floor(min(y[1] for _, points in relative for _, y in points) / 5)
	r_max = 5 * math.ceil(max(y[2] for _, points in relative for _, y in points) / 5)
	subtitle = 'Ryzen 9 9950X3D  |  CPU 9  |  boost enabled  |  Klaus 6502 functional test'
	revision = data['metadata'].get('source_revision')
	if revision:
		subtitle = f'Ryzen 9 9950X3D  |  CPU 9  |  boost enabled  |  Klaus 6502  |  mk6502 {revision[:7]}'
	notes = ('GCC 16.1.1 -O2  |  median of seven interleaved rounds  |  whiskers show interquartile ranges',)
	data = ('Tail-jump runtime versus AL-token stalls', 'Core cycles per guest instruction', 'AL stall cycles per guest instruction', tuple(range(x_min, x_max+1)), tuple(range(y_min, y_max+1)), absolute)
	draw_figure(f'{name}-sweep.svg', subtitle, entries, data, notes)
	data = ('Tail-jump runtime by dependency depth', 'Change in cycles per guest instruction (%)', 'LEAs made dependent on the previous LEA', (0, 8, 16, 24, 32), tuple(range(r_min, r_max+1, 5)), relative)
	draw_figure(f'{name}-dependency-depth.svg', subtitle, entries, data, (*notes, 'Baseline is the independent case from the same round and LEA count.'))


if __name__ == '__main__':
	capacity()
	tail_jump('tail-jump')
	tail_jump('mk6502-tail-jump')
