#!/usr/bin/env python3
"""Plot published stable-presentation results at distinct follow-up horizons.

No treatment-risk, QALY, causal or joint patient-level model is estimated here.
"""
from pathlib import Path
import csv,json,sys
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

root=Path(sys.argv[1]);out=Path(sys.argv[2]);out.mkdir(parents=True,exist_ok=True)
qol=list(csv.DictReader((root/'data/stable-qol.csv').open()))
qol=qol[1:]
# Exact published unique-patient counts; the current main study carries this extraction.
counts={'Spontaneous MI':{'PCI':[30,456],'CABG':[11,454]},
        'Repeat revascularization':{'PCI':[66,456],'CABG':[30,454]},
        'Death':{'PCI':[32,456],'CABG':[30,454]}}
plt.rcParams.update({'font.size':11,'axes.titlesize':13,'axes.labelsize':11,'font.family':'DejaVu Sans','pdf.fonttype':42})
fig,(a,b)=plt.subplots(1,2,figsize=(12.6,6.8),gridspec_kw={'width_ratios':[1,1.25]})
fig.subplots_adjust(left=.12,right=.97,bottom=.32,top=.77,wspace=.66)
blue='#216a9c';teal='#237b65';ink='#16354a'
fig.suptitle('PCI and CABG: recovery and later events',x=.12,ha='left',y=.97,fontsize=19,fontweight='bold',color=ink)
fig.text(.12,.90,'FAME-3 stable-presentation subgroup | Published aggregate outcomes',fontsize=11,color='#405c70')
y=np.array([1,0]);x=np.array([float(r['adjusted_difference']) for r in qol]);lo=np.array([float(r['lower_95']) for r in qol]);hi=np.array([float(r['upper_95']) for r in qol])
a.errorbar(x,y,xerr=np.vstack([x-lo,hi-x]),fmt='o',color=blue,capsize=5,lw=2,ms=7)
a.axvline(0,color='#657b8a',lw=1,ls='--');a.set_yticks(y,['1 month','12 months']);a.set_xlim(-.035,.095);a.set_ylim(-.55,1.6)
a.set_xlabel('Adjusted EQ-5D difference\nPCI minus CABG (95% CI)');a.set_title('A. Reported health status',loc='left',pad=19,color=ink)
for xx,yy,ll,hh in zip(x,y,lo,hi):a.text(-.033,yy+.29,f'{xx:+.3f} ({ll:+.3f} to {hh:+.3f})',fontsize=9,color=ink)
a.text(.03,-.48,'Higher favors PCI',fontsize=9,color=ink,ha='center')
labels=list(counts); yy=np.arange(3)[::-1]
for name,color,offset in [('PCI',blue,.10),('CABG',teal,-.10)]:
 vals=[counts[k][name][0]/counts[k][name][1]*100 for k in labels]
 b.scatter(vals,yy+offset,color=color,s=38,label=name,zorder=3)
 for value,pos,k in zip(vals,yy+offset,labels):
  num,den=counts[k][name]
  b.text(value+.38,pos,f'{num}/{den}',ha='left',va='center',fontsize=9,color=color)
b.set_yticks(yy,labels);b.set_xlim(0,17.5);b.set_xticks([0,5,10,15]);b.set_ylim(-.5,2.6)
b.set_xlabel('Reported five-year crude fraction (%)');b.set_title('B. Reported five-year events',loc='left',pad=19,color=ink)
b.legend(frameon=False,loc='lower right',fontsize=10)
for ax in (a,b):
 ax.spines[['top','right']].set_visible(False);ax.spines[['left','bottom']].set_color('#bdcbd4');ax.tick_params(axis='both',length=0,pad=7);ax.grid(axis='x',color='#e5ebef',lw=.7,zorder=0)
fig.text(.12,.14,'Different outcomes and time windows: these panels do not estimate a net clinical benefit or a treatment rule.',fontsize=9.5,color=ink)
fig.text(.12,.055,'EQ-5D: Fearon et al., Circulation 2022, appendix Table S3; adjusted for baseline diabetes.\nEvents: Fearon et al., Lancet 2025, appendix Table S9. Crude fractions do not adjust for censoring;\nstable-specific follow-up completeness is unavailable. A near-zero estimate does not establish equivalence.',fontsize=8.6,color='#405c70',linespacing=1.5)
fig.savefig(out/'stable-recovery-and-events.png',dpi=180,facecolor='white')
fig.savefig(out/'stable-recovery-and-events.pdf',facecolor='white',metadata={'Title':'PCI and CABG: published stable-presentation recovery and later events'})
plt.close(fig)
print(out/'stable-recovery-and-events.pdf')
