#!/usr/bin/env python3
"""Render original publication figures from the archived experiment results."""
import json
from pathlib import Path
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

HERE=Path(__file__).resolve().parent
OUT=HERE/'figures'
OUT.mkdir(exist_ok=True)
r=json.loads((HERE/'results.json').read_text())
e=json.loads((HERE/'empirical-results.json').read_text())
plt.rcParams.update({'font.family':'DejaVu Sans','font.size':11,'axes.titlesize':14,
                     'axes.labelsize':11,'figure.facecolor':'white','axes.facecolor':'white',
                     'axes.spines.top':False,'axes.spines.right':False,'svg.fonttype':'none'})
blue='#2364AA';orange='#D4651B';gray='#6B7280';red='#C33149';green='#00896A'

def save(fig,name,locale):
    fig.savefig(OUT/f'{name}-{locale}.svg',bbox_inches='tight')
    fig.savefig(OUT/f'{name}-{locale}.png',dpi=170,bbox_inches='tight')
    plt.close(fig)

for es in [False,True]:
    locale='es' if es else 'en'
    fig,ax=plt.subplots(figsize=(10.8,5.5))
    pmfs=[r['fixed_lists']['profiles'][0]['pmf'],r['fixed_lists']['profiles'][1]['pmf'],r['fixed_lists']['poisson_mean_matched']['pmf']]
    labels=['Dos tiros de 0.60','Doce tiros de 0.10','Poisson: media = 1.20'] if es else ['Two shots at 0.60','Twelve shots at 0.10','Poisson: mean = 1.20']
    for i,(a,label,color) in enumerate(zip(pmfs,labels,[blue,orange,gray])):
        vals=[(a[j] if j<len(a) else 0)*100 for j in range(6)]+[sum(a[6:])*100]
        ax.bar(np.arange(7)+(i-1)*.24,vals,width=.22,label=label,color=color)
    ax.set_xticks(range(7),['0','1','2','3','4','5','≥6'])
    ax.set_ylabel('Probabilidad (%)' if es else 'Probability (%)')
    ax.set_xlabel('Número de goles' if es else 'Number of goals')
    ax.set_title('El mismo xG, distintas distribuciones de goles' if es else 'Identical xG totals, different goal distributions',loc='left',weight='bold',pad=16)
    ax.set_ylim(0,55);ax.grid(axis='y',alpha=.15);ax.set_axisbelow(True)
    ax.legend(frameon=False,ncol=3,loc='upper right',fontsize=10)
    note='Experimento exacto sintético · listas de tiros fijas e independientes · xG = 1.20' if es else 'Exact synthetic experiment · fixed independent shot lists · xG = 1.20'
    fig.text(.125,-.015,note,fontsize=10,color=gray)
    save(fig,'equal-xg-distributions',locale)

    fig,ax=plt.subplots(figsize=(10.8,5.3))
    rows=r['time_resolution']['rows'];hz=[x['hertz'] for x in rows]
    ax.plot(hz,[100*x['naive_repeated_probability'] for x in rows],'-o',color=red,lw=2.4,label='Repetir el riesgo de 1 segundo' if es else 'Repeat the 1-second risk at every frame')
    ax.plot(hz,[100*x['corrected_probability'] for x in rows],'-o',color=blue,lw=2.4,label='Riesgo transformado por intervalo' if es else 'Convert risk to each nonoverlapping interval')
    ax.set_xticks(hz);ax.set_ylim(0,105)
    ax.set_xlabel('Frecuencia de muestreo (Hz)' if es else 'Sampling frequency (Hz)')
    ax.set_ylabel('Probabilidad de al menos un gol (%)' if es else 'Probability of at least one goal (%)')
    ax.set_title('Una probabilidad no es independiente del intervalo temporal' if es else 'Probability belongs to a time interval',loc='left',weight='bold',pad=16)
    ax.grid(axis='y',alpha=.15);ax.legend(frameon=False,loc='center right')
    ax.annotate('25 Hz: 92.00%',xy=(25,91.9969),xytext=(28,80),color=red,arrowprops={'arrowstyle':'-','color':red})
    ax.annotate('9.61%',xy=(50,9.6079),xytext=(43,19),color=blue,arrowprops={'arrowstyle':'-','color':blue})
    note='Ejemplo sintético: 2% por segundo durante 5 s; intensidad constante supuesta.' if es else 'Synthetic example: 2% per second for 5 s; assumes a constant hazard.'
    fig.text(.125,-.015,note,fontsize=10,color=gray)
    save(fig,'time-resolution',locale)

    fig,axs=plt.subplots(1,2,figsize=(11.5,4.8))
    contrasts=['geometry_minus_constant','geometry_recalibrated_minus_geometry']
    labels=['Geometría − constante','Recalibrado − geometría'] if es else ['Geometry − constant','Recalibrated − geometry']
    for ax,metric,title in zip(axs,['brier','log_loss'],['Diferencia de Brier' if es else 'Difference in Brier score','Diferencia de pérdida logarítmica' if es else 'Difference in log loss']):
        for y,(contrast,label,color) in enumerate(zip(contrasts,labels,[blue,orange])):
            q=e['paired_differences'][contrast][metric]
            ax.errorbar(q['value'],y,xerr=[[q['value']-q['ci95'][0]],[q['ci95'][1]-q['value']]],fmt='o',color=color,elinewidth=2.5,capsize=5,markersize=7)
        ax.axvline(0,color=gray,ls='--',lw=1)
        ax.set_yticks(range(2),labels,fontsize=10);ax.invert_yaxis();ax.set_ylim(1.6,-.6)
        ax.set_title(title,weight='bold',loc='left',pad=16)
        ax.set_xlabel('Un valor negativo favorece el primer modelo' if es else 'Negative values favor the first model',fontsize=9)
        ax.grid(axis='x',alpha=.15)
    fig.suptitle('Datos reales: el beneficio de la recalibración no quedó establecido' if es else 'Real data: the recalibration benefit was not established',ha='left',x=.03,y=1.04,weight='bold',fontsize=15)
    fig.tight_layout(w_pad=3)
    note='Evaluación: 76 partidos / 1,630 tiros · IC 95% pareado, 2,000 remuestreos por partido · Wyscout 2017/18, CC BY 4.0' if es else 'Evaluation: 76 matches / 1,630 shots · paired 95% CI, 2,000 match bootstraps · Wyscout 2017/18, CC BY 4.0'
    fig.text(.03,-.04,note,fontsize=9,color=gray)
    save(fig,'empirical-comparison',locale)
