from pathlib import Path
import json,math
import numpy as np
from scipy.stats import norm
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

ROOT=Path(__file__).resolve().parents[1]


def run():
    d=json.loads((ROOT/'data/target-forest-inputs.json').read_text())
    r=json.loads((ROOT/'results/R1.json').read_text())
    rows=d['labelled_death_disabling_stroke']['1_year']
    repaired={k:list(v) for k,v in rows.items()}
    repaired['DEDICATE']=d['confirmed_endpoint_substitutions']['DEDICATE']['source_death_disabling_stroke']
    repaired['UKTAVI']=d['confirmed_endpoint_substitutions']['UKTAVI']['source_death_disabling_nonfatal_stroke']
    names=list(rows)
    fig,ax=plt.subplots(figsize=(10,7),layout='constrained')
    def show_row(values,y,color,label=None,marker='o'):
        a,n1,c,n0=values;rr=(a/n1)/(c/n0);se=math.sqrt(1/a-1/n1+1/c-1/n0);lo,hi=np.exp(np.log(rr)+np.array([-1,1])*norm.ppf(.975)*se)
        ax.errorbar(rr,y,xerr=[[rr-lo],[hi-rr]],fmt=marker,color=color,capsize=3,label=label,markersize=6)
    for i,name in enumerate(names):
        y=len(names)-i
        if name in ['DEDICATE','UKTAVI']:
            show_row(rows[name],y+.12,'#919ca1','Target displayed input' if name=='DEDICATE' else None)
            show_row(repaired[name],y-.12,'#146d87','Intended endpoint substituted' if name=='DEDICATE' else None)
        else:show_row(rows[name],y,'#33424a')
    for label,key,y,color in [('Original pooled','original',-.15,'#919ca1'),('Two endpoint substitutions','changed',-.85,'#146d87')]:
        x=r['reproduction']['labelled_death_disabling_stroke']['1_year'] if key=='original' else r['sensitivities']['1_year_two_endpoint_substitutions']
        rr=x['risk_ratio'];lo,hi=x['ci_hk'];ax.errorbar(rr,y,xerr=[[rr-lo],[hi-rr]],fmt='D',color=color,capsize=5,markersize=8)
        ax.text(3.5,y,f"{rr:.2f} ({lo:.2f}–{hi:.2f})",va='center',fontsize=10)
    ax.axvline(1,color='#666666',ls='--',lw=1)
    ax.set_yticks(list(range(len(names),0,-1))+[-.15,-.85],names+['Original pooled','Two endpoint substitutions'])
    ax.set_xscale('log');ax.set_xlim(.1,12);ax.set_ylim(-1.3,len(names)+.7)
    ax.set_xticks([.1,.2,.5,1,2,5,10],['0.1','0.2','0.5','1','2','5','10'])
    ax.set_xlabel('Count-based risk ratio, TAVR / surgery; 95% CI')
    ax.set_title('One-year composite: two source-backed endpoint substitutions',loc='left',weight='bold')
    ax.legend(loc='upper right',frameon=True)
    ax.grid(axis='x',alpha=.15);ax.spines[['top','right','left']].set_visible(False)
    fig.savefig(ROOT/'results/figure1.png',dpi=180);plt.close(fig)

    full=r['sensitivities']['1_year_two_endpoint_substitutions']
    loo=r['sensitivities']['1_year_two_substitutions_leave_one_out']
    items=[('All six target rows, two substitutions',full)]+[('Omit '+k,v) for k,v in loo.items()]
    fig,ax=plt.subplots(figsize=(10,5.8),layout='constrained')
    for i,(name,x) in enumerate(items):
        y=len(items)-1-i;rr=x['risk_ratio'];lo,hi=x['ci_hk'];color='#146d87' if i==0 else '#485962'
        ax.errorbar(rr,y,xerr=[[rr-lo],[hi-rr]],fmt='D' if i==0 else 'o',color=color,capsize=4)
        ax.text(1.42,y,f"{rr:.2f} ({lo:.2f}–{hi:.2f})",va='center',fontsize=10)
    ax.axvline(1,color='#666666',ls='--',lw=1);ax.set_xscale('log');ax.set_xlim(.25,3.3)
    ax.set_xticks([.25,.5,1,2],['0.25','0.5','1','2']);ax.set_yticks(range(len(items)-1,-1,-1),[x[0] for x in items])
    ax.set_xlabel('Count-based pooled risk ratio; Hartung–Knapp 95% CI')
    ax.set_title('Leave-one-trial-out uncertainty after two endpoint substitutions',loc='left',weight='bold')
    ax.grid(axis='x',alpha=.15);ax.spines[['top','right','left']].set_visible(False)
    fig.savefig(ROOT/'results/figure2.png',dpi=180);plt.close(fig)

    horizons=d['longest_horizon_years'];fig,ax=plt.subplots(figsize=(9,4.5),layout='constrained')
    for i,(name,h) in enumerate(horizons.items()):
        ax.plot([0,h],[i,i],color='#adb8bd',lw=2)
        ax.scatter([h],[i],s=70,color='#bc6332' if h==1 else '#146d87')
        ax.text(h+.15,i,str(h)+' y',va='center')
    ax.set_yticks(range(len(horizons)),list(horizons));ax.invert_yaxis();ax.set_xlim(0,11)
    ax.set_xlabel('Outcome follow-up used in the target’s “≥1-year” panel (years)')
    ax.set_title('The longest-follow-up panel combines different horizons',loc='left',weight='bold')
    ax.spines[['top','right','left']].set_visible(False);ax.grid(axis='x',alpha=.15)
    fig.savefig(ROOT/'results/figure3.png',dpi=180);plt.close(fig)


if __name__=='__main__':run()
