"""Test the distance observable of the published case using the archived experimental files."""
import csv, json
from pathlib import Path
from hashlib import sha256
from datetime import datetime, timezone
from Bio.PDB.MMCIF2Dict import MMCIF2Dict
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
root=Path(__file__).resolve().parents[1]
def run():
    rows=[]
    for code in ('1SUG','5K9W','5K9V','1T49'):
        source=root/('sources/case' if code=='1SUG' else 'data/raw')/f'{code}.cif'
        d=MMCIF2Dict(str(source))
        assert d['_entry.id']==[code]
        at={}
        fields=('group_PDB','pdbx_PDB_model_num','auth_asym_id','auth_seq_id','auth_comp_id','auth_atom_id','occupancy','label_alt_id','Cartn_x','Cartn_y','Cartn_z')
        for group,model,chain,index,res,atom,occ,alt,*v in zip(*(d['_atom_site.'+k] for k in fields)):
            if group=='ATOM' and model=='1' and chain=='A' and (index,res) in [('181','ASP'),('215','CYS')]:
                key=(index,atom);order=(float(occ),alt=='.',alt=='A')
                if key not in at or order>at[key][0]:at[key]=(order,np.array(v,dtype=float))
        for a,b in [('CA','CA'),('CG','SG'),('OD1','SG'),('OD2','SG')]:
            rows.append(dict(structure=code,chain='A',atom_181=a,atom_215=b,distance_A=float(np.linalg.norm(at['181',a][1]-at['215',b][1])),sha256=sha256(source.read_bytes()).hexdigest()))
    with (root/'independent/case_distances.csv').open('w',newline='') as f:
        w=csv.DictWriter(f,fieldnames=rows[0]);w.writeheader();w.writerows(rows)
    with (root/'independent/case_distances.csv').open() as f:ca=[x for x in csv.DictReader(f) if x['atom_181']=='CA']
    fig,ax=plt.subplots(figsize=(7.2,3.6),layout='constrained')
    labels=['1SUG · apo','5K9W · TCS401','5K9V · apo','1T49 · BB inhibitor']
    values=[float(r['distance_A']) for r in ca]
    colors=['#2e657e','#2e657e','#15867d','#15867d']
    bars=ax.barh(labels,values,color=colors,height=.55)
    ax.bar_label(bars,fmt='%.2f Å',padding=7)
    ax.invert_yaxis();ax.set_xlim(0,15.2);ax.set_xlabel('Asp181 Cα to Cys215 Cα separation (Å)');ax.set_title('The two apo crystals capture different WPD-loop states',loc='left',fontsize=13,weight='bold',pad=14)
    ax.spines[['top','right','left']].set_visible(False);ax.tick_params(length=0);ax.set_axisbelow(True);ax.grid(axis='x',alpha=.18)
    fig.savefig(root/'independent/figures/S3_case_geometry.png',dpi=170,bbox_inches='tight',pad_inches=.3)
    plt.close(fig)
if __name__=='__main__':run()
