"""Paired sphere quadrature to measure ligand shielding directly in a fixed 1T49 model."""
from pathlib import Path
import csv
from Bio.PDB import PDBParser
from scipy.spatial.distance import cdist
from scipy.spatial.transform import Rotation
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
root=Path(__file__).resolve().parents[1]
radii={'C':1.70,'O':1.52,'N':1.55,'S':1.80,'BR':1.85}
def atoms(residues):
    atoms=[a for r in residues for a in r if a.element in radii]
    return np.stack([a.coord for a in atoms]).astype(float),np.array([radii[a.element]+1.4 for a in atoms])
def caps(x,r,i,y,s,indices):
    delta=y[indices]-x[i]
    h=(r[i]**2+np.sum(delta**2,axis=1)-s[indices]**2)/(2*r[i])
    return delta.T,h
def run():
    c=PDBParser(QUIET=True).get_structure('1T49',root/'data/raw/1T49.pdb')[0]['A']
    x,r=atoms([v for v in c if v.id[0]==' ']);y,s=atoms([v for v in c if v.resname=='892'])
    near=cdist(x,y)<r[:,None]+s
    targets=[]
    for i in np.where(near.any(axis=1))[0]:
        nearby=np.linalg.norm(x-x[i],axis=1)<(r+r[i]);nearby[i]=False
        targets.append((r[i],caps(x,r,i,x,r,nearby),caps(x,r,i,y,s,near[i])))
    rows=[]
    for n in (240,960,3840,15360):
        idx=np.arange(n); z=1-2*(idx+.5)/n;h=np.sqrt(1-z*z)
        a=idx*np.pi*(3-np.sqrt(5));p=np.stack([h*np.cos(a),h*np.sin(a),z],axis=1)
        for rotation in (0,47,109):
            v=Rotation.from_euler('xyz',[rotation,rotation*.7,rotation*.3],degrees=True).apply(p)
            area=0
            for radius,(pdir,ph),(ldir,lh) in targets:
                exposed=(v@pdir<=ph).all(axis=1)
                shielded=(v@ldir>lh).any(axis=1)
                area+=4*np.pi*radius**2*np.mean(exposed & shielded)
            rows.append(dict(points_per_atom=n,rotation_degrees=rotation,protein_occluded_A2=area))
    table=root/'independent/sasa_convergence.csv'
    with table.open('w',newline='') as f:
        w=csv.DictWriter(f,fieldnames=rows[0]);w.writeheader();w.writerows(rows)
    with table.open() as f:records=list(csv.DictReader(f))
    fig,ax=plt.subplots(figsize=(6.5,3.3),layout='constrained')
    for rot,col in zip((0,47,109),('#167a82','#976c30','#7971a6')):
        rr=[v for v in records if int(v['rotation_degrees'])==rot];ax.plot([int(v['points_per_atom']) for v in rr],[float(v['protein_occluded_A2']) for v in rr],'o-',color=col,label=f'{rot}°')
    ax.set_xscale('log',base=4);ax.set_xticks([240,960,3840,15360],['240','960','3,840','15,360'])
    ax.set(xlabel='Surface points per atom',ylabel='Protein area shielded (Å²)')
    ax.set_title('1T49  |  Numerical sensitivity of the surface estimate',loc='left',fontsize=13,weight='bold',pad=12);ax.legend(title='Grid rotation',frameon=False,ncols=3)
    ax.spines[['top','right']].set_visible(False);ax.grid(axis='y',alpha=.2);fig.savefig(root/'independent/figures/S4_surface_convergence.png',dpi=170,bbox_inches='tight',pad_inches=.3)
    print([(v['rotation_degrees'],round(v['protein_occluded_A2'],2)) for v in rows[-3:]])
if __name__=='__main__':run()
