"""Scientific figures generated entirely from original calculations."""
import json
from pathlib import Path
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

ROOT=Path(__file__).resolve().parents[1];OUT=ROOT/'results'
x=json.loads((OUT/'R1.json').read_text())
plt.rcParams.update({'font.size':11,'axes.spines.top':False,'axes.spines.right':False,
                     'svg.hashsalt':'avr-survival-bounds-20261104'})

fig,ax=plt.subplots(figsize=(10,4.8),layout='constrained')
ids=['partner_L1_T5','partner_L1_T7','partner_L5_T7']
labels=['Survive year 1 under both; death by year 5',
        'Survive year 1 under both; death by year 7',
        'Survive year 5 under both; death by year 7']
for y,key in enumerate(ids[::-1]):
    r=x['partner'][key]
    ax.plot([r['rounding_lower_pp'],r['rounding_upper_pp']],[y,y],color='#b6d6ed',lw=13,solid_capstyle='butt')
    ax.plot([r['lower_pp'],r['upper_pp']],[y,y],color='#12699b',lw=5,solid_capstyle='butt')
    ax.scatter([r['lower_pp'],r['upper_pp']],[y,y],color='#12699b',s=35,zorder=3)
ax.axvline(0,color='#4d555b',lw=1,ls='--')
ax.set_yticks(range(3),labels[::-1]);ax.set_ylim(-.6,2.6)
ax.set_xlabel('TAVR minus surgery late-death risk difference (percentage points)')
ax.set_title('PARTNER 3: landmark choice changes the conditional identified set',loc='left',weight='bold',pad=18)
ax.plot([],[],color='#12699b',lw=5,label='Sharp bounds at displayed risks')
ax.plot([],[],color='#b6d6ed',lw=9,label='Envelope allowing rounding of each risk')
ax.legend(loc='lower right',fontsize=9,frameon=False)
fig.text(.5,-.025,'Identification bounds, not confidence intervals. Each row concerns a different potential-survivor population.',ha='center',fontsize=9)
fig.savefig(OUT/'figure1.png',dpi=180,bbox_inches='tight');plt.close(fig)

row=x['partner']['partner_L5_T7']
fig,axes=plt.subplots(1,2,figsize=(14,6.3),layout='constrained')
labels=['Death by year 5','Death during years 5–7','Alive at year 7']
for ax,key,title in zip(axes,['selection_only','all_always_survive_horizon'],
    ['Equal binary late-death outcomes in always-survivors',
     'Every always-survivor remains alive through year 7']):
    r=row[key];p=np.array(r['witness'])*100
    ax.imshow(p,cmap='Blues',vmin=0,vmax=85)
    ax.set_xticks(range(3),labels,rotation=20,ha='right');ax.set_yticks(range(3),labels)
    ax.set_xlabel('Potential surgical outcome',labelpad=10)
    for i in range(3):
        for j in range(3):ax.text(j,i,f'{p[i,j]:.1f}%',ha='center',va='center',fontsize=15,color='white' if p[i,j]>40 else '#10384f')
    ax.add_patch(plt.Rectangle((.5,.5),2,2,fill=False,edgecolor='#b86716',lw=3))
    pct=100*r['minimum_early_survival_discordance']
    ax.set_title(title+f'\nMinimum survival discordance in this class: {pct:.1f}%',
                 loc='left',fontsize=10,weight='bold',pad=15)
    ax.tick_params(length=0,labelsize=10)
axes[0].set_ylabel('Potential transcatheter outcome',labelpad=10)
fig.suptitle('Two constructed populations with the same marginal mortality risks',fontsize=14,weight='bold')
fig.text(.5,-.025,'Witnesses of mathematical feasibility, not estimated patient strata or claims of clinical plausibility.',ha='center',fontsize=10)
fig.savefig(OUT/'figure2.png',dpi=180,bbox_inches='tight');plt.close(fig)

g=x['omission_sensitivity']['grid']
fig,axes=plt.subplots(1,2,figsize=(12.5,4.8),layout='constrained')
source=json.loads((ROOT/'data/mortality_inputs.json').read_text())['primary_source']
omitted_pct=100*(1-source['n_SAVR']/source['randomized_SAVR'])
for ax,lo,hi,title in zip(axes,['overall_lower_pp','lower_pp'],['overall_upper_pp','upper_pp'],
    ['Overall mortality by year 7','Late death among always-survivors at year 1']):
    a=np.array([[r['omitted_SAVR_pct'],r[lo],r[hi]] for r in g])
    ax.fill_between(a[:,0],a[:,1],a[:,2],color='#dceaf3');ax.plot(a[:,0],a[:,1],color='#12699b');ax.plot(a[:,0],a[:,2],color='#12699b')
    ax.axhline(0,color='#4d555b',ls='--',lw=1)
    ax.axvline(omitted_pct,color='#b86716',lw=1.5,label='Diagram’s omitted fraction')
    ax.set_xlabel('Outcome-unrestricted omitted surgery fraction (%)',fontsize=9)
    ax.set_ylabel('TAVR minus surgery risk difference\n(percentage points)')
    ax.set_title(title,loc='left',fontsize=11,weight='bold')
    ax.legend(loc='lower left',frameon=True,facecolor='white',framealpha=1,edgecolor='white',fontsize=8)
fig.suptitle('Aligned-horizon allocation-to-initiation sensitivity model',weight='bold',fontsize=13)
fig.text(.5,-.03,'Model bounds, not intention-to-treat estimates or confidence intervals. TAVR selected fraction fixed at 496/503.',ha='center',fontsize=9)
fig.savefig(OUT/'figure3.png',dpi=180,bbox_inches='tight');plt.close(fig)

r=x['shared_early_death_sensitivity'];a=np.array([[v['common_early_death_pct'],v['lower_pp'],v['upper_pp']] for v in r['grid']])
fig,ax=plt.subplots(figsize=(8.7,4.8),layout='constrained')
ax.fill_between(a[:,0],a[:,1],a[:,2],color='#dceaf3');ax.plot(a[:,0],a[:,1],color='#12699b');ax.plot(a[:,0],a[:,2],color='#12699b')
ax.axhline(0,color='#4d555b',ls='--',lw=1)
ax.axvspan(0,r['strong_null_common_death_ceiling_pct'],color='#f3d8b7',alpha=.8,label='All always-survivors alive through year 7 is feasible')
ax.axvline(r['binary_null_common_death_ceiling_pct'],color='#b86716',lw=1.5,label='Largest common-death mass permitting a binary null')
ax.set_xlabel('Population who would die by year 5 under both strategies (%)')
ax.set_ylabel('Conditional late-death risk difference\n(percentage points)')
ax.set_title('Unobserved shared early mortality changes the identified set',loc='left',weight='bold')
ax.legend(loc='lower right',frameon=True,facecolor='white',framealpha=1,edgecolor='white',fontsize=8)
fig.text(.5,-.03,'PARTNER 3, years 5–7. These are assumptions about counterfactual association, not observed patient groups or confidence intervals.',ha='center',fontsize=9)
fig.savefig(OUT/'figure4.png',dpi=180,bbox_inches='tight');plt.close(fig)
print('Generated four scientific figures from the declared calculations.')
