"""Render stored retrieval observations as accessible desktop and mobile SVGs."""
from pathlib import Path
import json
import re

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.ticker import PercentFormatter

ROOT = Path(__file__).resolve().parents[3]
OUT = Path(__file__).resolve().parent
DATA = json.loads((ROOT / 'docs/assets/bench/persona-recall.json').read_text())
ROWS = DATA['steps']
X = [row['entities'] for row in ROWS]
plt.rcParams.update({
    'font.family': 'DejaVu Sans', 'font.size': 14, 'svg.fonttype': 'none',
    'svg.hashsalt': 'synapse-persona-recall-visuals-1',
    'axes.spines.top': False, 'axes.spines.right': False,
    'axes.spines.left': False, 'axes.spines.bottom': False,
    'text.color': '#1A1A1A', 'axes.labelcolor': '#5F596B',
    'xtick.color': '#5F596B', 'ytick.color': '#5F596B',
})
DESCRIPTION = (
    'Twenty fixed target questions across six measured corpus sizes, from 77 to 463 '
    'entities. First-result recall is 75, 90, 85, 85, 85 and 85 percent; top-ten recall '
    'is 95, 100, 100, 100, 100 and 100 percent. Internal macOS arm64 engineering '
    'fixture; original run source commit unknown.'
)


def draw(mobile=False):
    """Plot every recorded point without inference, smoothing or invented baselines."""
    fig, ax = plt.subplots(figsize=(6, 10) if mobile else (12, 6.2), dpi=100)
    fig.patch.set_facecolor('#F6F4EF')
    ax.set_facecolor('#F6F4EF')
    fig.subplots_adjust(left=.13 if mobile else .10, right=.95 if mobile else .96,
                        bottom=.28 if mobile else .25, top=.67 if mobile else .70)
    if mobile:
        fig.text(.06, .95, 'SYNAPSE / RETRIEVAL EVIDENCE', fontsize=14,
                 color='#5B3EE0', weight='bold')
        fig.text(.06, .89, 'Does the target fact', fontsize=25, weight='bold')
        fig.text(.06, .845, 'stay within reach?', fontsize=25, weight='bold')
        fig.text(.06, .79, '20 fixed questions. Six synthetic contexts.',
                 fontsize=14, color='#5F596B')
        fig.text(.06, .755, '77 to 463 entities in one workspace.',
                 fontsize=14, color='#5F596B')
    else:
        fig.text(.05, .925, 'SYNAPSE / RECORDED RETRIEVAL EVIDENCE', fontsize=13,
                 color='#5B3EE0', weight='bold')
        fig.text(.05, .85, 'Does the target fact stay within reach?',
                 fontsize=26, weight='bold')
        fig.text(.05, .79, 'One fixed set of 20 questions. Six synthetic contexts added '
                 'to the same workspace.', fontsize=14, color='#5F596B')
    first = [row['recall_at_1'] for row in ROWS]
    top_ten = [row['recall_at_k'] for row in ROWS]
    ax.plot(X, top_ten, 'o-', color='#5B3EE0', linewidth=3.5, markersize=7,
            label='Within the first 10 results')
    ax.plot(X, first, 's-', color='#7E5418', linewidth=2.5, markersize=6,
            label='First result')
    ax.set_ylim(0, 1.15 if mobile else 1.1)
    ax.set_yticks([0, .25, .5, .75, 1])
    ax.yaxis.set_major_formatter(PercentFormatter(1))
    ax.set_xticks(X)
    ax.set_xlabel('Entities in the measured corpus', labelpad=12, fontsize=14)
    if not mobile:
        ax.set_ylabel('Target fact retrieved', labelpad=14)
    ax.grid(axis='y', color='#D5CFE5', linewidth=.9)
    ax.set_axisbelow(True)
    ax.tick_params(length=0, pad=9, labelsize=14)
    ax.legend(loc='lower right', frameon=False, fontsize=14 if mobile else 13)
    for values, offset in [(top_ten, 11), (first, -23)]:
        for px, py in zip(X, values):
            ax.annotate(f'{py:.0%}', (px, py), textcoords='offset points',
                        xytext=(0, offset), ha='center', fontsize=14 if mobile else 12,
                        color='#1A1A1A')
    if mobile:
        for y, text in [(.18, 'Internal synthetic fixture, macOS arm64.'),
                        (.145, 'Original run source commit: unknown.'),
                        (.09, 'Source: docs/assets/bench/persona-recall.json'),
                        (.055, 'These observations do not predict other workloads.')]:
            fig.text(.06, y, text, fontsize=14, color='#5F596B')
    else:
        fig.text(.05, .065, 'Internal synthetic fixture, macOS arm64. Original run '
                 'source commit: unknown.', fontsize=12, color='#5F596B')
        fig.text(.05, .025, 'Source: docs/assets/bench/persona-recall.json. These observations '
                 'do not predict other workloads.', fontsize=12, color='#5F596B')
    output = OUT / ('retrieval-evidence-mobile.svg' if mobile else 'retrieval-evidence.svg')
    fig.savefig(output, metadata={'Date': None, 'Title': 'Recorded synthetic retrieval observations',
                                 'Description': DESCRIPTION})
    plt.close(fig)
    svg = output.read_text()
    svg = re.sub(r'(<svg\b[^>]*)(>)',
                 r'\1 role="img" aria-labelledby="retrieval-title retrieval-desc"\2',
                 svg, count=1)
    svg = re.sub(r'(<svg\b[^>]*>)',
                 r'\1<title id="retrieval-title">Recorded synthetic retrieval observations</title>'
                 '<desc id="retrieval-desc">' + DESCRIPTION + '</desc>', svg, count=1)
    output.write_text("\n".join(line.rstrip() for line in svg.splitlines()) + "\n")


if __name__ == '__main__':
    draw()
    draw(mobile=True)
