"""Fixed-coordinate ligand occlusion and cutoff sensitivity in deposited 1T49 chain A."""
from pathlib import Path
import csv, json
from Bio.PDB import PDBParser
from Bio.PDB.SASA import ShrakeRupley
from scipy.spatial.distance import cdist
import numpy as np

root = Path(__file__).resolve().parents[1]
out = root/'independent'
def write_csv(name, rows):
    with (out/name).open('w', newline='') as f:
        w=csv.DictWriter(f,fieldnames=rows[0].keys())
        w.writeheader()
        w.writerows(rows)

def run():
    chain=PDBParser(QUIET=True).get_structure('1T49',root/'data/raw/1T49.pdb')[0]['A']
    residues=[r for r in chain if r.id[0]==' ']
    ligand=next(r for r in chain if r.resname=='892')
    for r in list(chain):
        if r not in residues and r is not ligand:
            chain.detach_child(r.id)
    xyz=lambda r: np.array([a.coord for a in r if a.element not in ('H','D')])
    distances={r.id[1]: float(cdist(xyz(r),xyz(ligand)).min()) for r in residues}
    cutoffs=[]
    for cutoff in (3,3.5,4,4.5,5,5.5,6):
        ids=[i for i,d in distances.items() if d<=cutoff]
        cutoffs.append(dict(cutoff_A=cutoff,n_residues=len(ids),author_residues=' '.join(map(str,ids))))
    write_csv('shell_sensitivity.csv',cutoffs)
    rows=[]
    for n in (240,960):
        sr=ShrakeRupley(probe_radius=1.4,n_points=n,radii_dict={'BR':1.85})
        sr.compute(chain,level='R')
        complex_area={r.id[1]:r.sasa for r in residues}
        chain.detach_child(ligand.id)
        sr.compute(chain,level='R')
        for r in residues:
            i=r.id[1]
            rows.append(dict(sphere_points=n,author_seq=i,residue=r.resname,nearest_ligand_A=distances[i],with_ligand_A2=complex_area[i],without_ligand_A2=r.sasa,occluded_A2=r.sasa-complex_area[i]))
        chain.add(ligand)
    write_csv('fixed_coordinate_sasa.csv',rows)
    report={}
    for n in (240,960):
        report[str(n)] = round(sum(r['occluded_A2'] for r in rows if r['sphere_points']==n),3)
    print('Protein solvent-accessible area occluded by deposited ligand (Å²):',report)
    print('Threshold sensitivity:', [(r['cutoff_A'],r['n_residues']) for r in cutoffs])
if __name__=='__main__':
    run()
