"""Render complementary figures from the independent audit tables."""
from pathlib import Path
import csv, json
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np

base=Path(__file__).resolve().parent
def read(file):
    with (base/file).open() as s:return list(csv.DictReader(s))
def style(ax):
    ax.spines[['top','right']].set_visible(False)
    ax.tick_params(length=0,pad=6)
    ax.set_axisbelow(True)
    ax.grid(color='#dbe5e5',lw=.8,axis='x')
def save(fig,file):
    path=base/'figures';path.mkdir(exist_ok=True)
    fig.savefig(path/(file+'.png'),dpi=170,bbox_inches='tight',pad_inches=.3,facecolor='white')
    plt.close(fig)
def run():
    plt.rcParams.update({'font.size':10,'font.family':'DejaVu Sans','axes.edgecolor':'#b7c6c6','axes.labelcolor':'#26494b','text.color':'#173d41'})
    rows=read('shell_sensitivity.csv')
    fig,ax=plt.subplots(figsize=(6.4,3.5),layout='constrained')
    x=[float(r['cutoff_A']) for r in rows];y=[int(r['n_residues']) for r in rows]
    ax.plot(x,y,'o-',c='#087e83',lw=2.2);ax.set(xlabel='Minimum ligand–residue heavy-atom distance cutoff (Å)',ylabel='Residues in shell',xticks=x)
    for a,b in zip(x,y):ax.annotate(str(b),(a,b),xytext=(0,8),textcoords='offset points',ha='center')
    ax.set_ylim(0,max(y)*1.15);style(ax);ax.set_title('1T49  |  Residue membership depends on shell radius',loc='left',weight='bold',pad=15)
    save(fig,'S1_shell_sensitivity')
    rows=read('fixed_coordinate_sasa.csv'); fine=sorted([r for r in rows if r['sphere_points']=='960'],key=lambda r:float(r['occluded_A2']),reverse=True)[:10][::-1]
    coarse={r['author_seq']:float(r['occluded_A2']) for r in rows if r['sphere_points']=='240'}
    fig,ax=plt.subplots(figsize=(6.4,4.6),layout='constrained')
    pos=np.arange(len(fine));ax.barh(pos,[float(r['occluded_A2']) for r in fine],color='#258b82',label='960 points/atom')
    ax.scatter([coarse[r['author_seq']] for r in fine],pos,s=19,color='#422a4e',label='240 points/atom')
    ax.set(yticks=pos,yticklabels=[r['residue'].title()+' '+r['author_seq'] for r in fine],xlabel='Loss of solvent-accessible area with ligand present (Å²)')
    ax.set_title('1T49  |  Largest ligand-shielded residue surfaces',loc='left',weight='bold',pad=15)
    ax.legend(frameon=False,loc='lower right');style(ax);save(fig,'S2_surface_occlusion')
if __name__=='__main__':run()
