"""Prospective tests of the iodine and chlorine structural and lifetime hypotheses."""
import json
import numpy as np
from contacts import draw_packing_contact
from contact_geometry import closest_contact
from geometry import fold_profile
from make_figures import salts
from plate import CHLORO, IODO, MUTED, PARENT, ROOT, Plate

p = Plate(103)
p.panel(1,3.3,'a','Iodine faces an outer-ring sulfur')
contact = closest_contact('R5_pI','I')
draw_packing_contact(p.axes(1,7.3,70,38.5),contact,'I',(-6,-3))

p.panel(73,3.3,'b','Ligand fold in the parent and iodine salts')
for x,salt,name in [(73,'SEED','Parent'),(126,'R5_pI','Iodine salt')]:
    p.text(x+26,12,name,ha='center',fontsize=8.4,weight='bold',
           color=PARENT if salt=='SEED' else IODO)
    profile=p.axes(x,15,52,34)
    fold_profile(profile,salt)
    if salt=='R5_pI':
        angle=np.radians(25)
        span=np.array([1.1,7.5])
        profile.plot(span*np.cos(angle),span*np.sin(angle),lw=.85,ls=(0,(2,2)),
                     color='#ae275d',zorder=2)
        p.line(145,46.8,149.5,46.8,ls=(0,(2,2)),lw=.85,color='#ae275d')
        p.text(151,46.8,'Forecast ≥25°',fontsize=7.3,color='#ae275d')

p.panel(1,53.5,'c','Calculated iodine spin lifetime vs parent')
with (ROOT/'preregistration'/'judge_receipt_R5_pI_rcpt-f0670a4fa30c.json').open() as f:
    ratios=json.load(f)['details']['paired_ratio']['per_sigma']
widths=[5,10,20]
changes=[100*(ratios[str(w)]-1) for w in widths]
ax=p.axes(16,62,69.5,31)
ax.axhline(0,color=MUTED,lw=.85,zorder=1)
ax.bar(range(3),changes,width=.47,color=IODO,zorder=2)
for j,(value,label) in enumerate(zip(changes,['Unexpected gain','','Loss as forecast'])):
    percent=f'{value:+.0f}%'.replace('-','−')
    annotation=(label+'\n'+percent if value>0 else percent+'\n'+label) if label else percent
    ax.annotate(annotation,(j,value),xytext=(0,2.2 if value>=0 else -2.8),
                textcoords='offset points',ha='center',va='bottom' if value>=0 else 'top',
                fontsize=7.3,weight='bold',color=IODO,linespacing=1.15)
ax.set(xlim=(-.62,2.62),ylim=(-46,75),yticks=[-20,0,20,40],
       yticklabels=['−20','0','+20','+40'],ylabel='Lifetime change (%)',
       xticks=range(3),xticklabels=['5','10','20'],xlabel='Vibrational linewidth (cm⁻¹)')
ax.spines['bottom'].set_visible(False)
ax.tick_params(axis='x',length=0)

p.panel(93,53.5,'d','Extra chlorine failed to keep the ligands flat')
with (ROOT/'preregistration'/'R5_pCl4_gate_result.json').open() as f:
    gate=json.load(f)['fold_gate']
limit=gate['threshold_deg']
single=float(salts['R4_pCl']['max_fold_deg'])
folds=[single,38.4,gate['max_deg']]
ax=p.axes(112.4,66,58,24)
ax.axvspan(0,limit,color='#edecf5',zorder=0)
ax.axvline(limit,ls=(0,(3,2)),color='#ae275d',lw=.9,zorder=1)
p.text(112.4+58*limit/48,61.5,f'Forecast ≤{limit:.0f}° for Cl₂ and Cl₄',
       ha='center',fontsize=7.25,color='#ae275d')
for j,value in enumerate(folds):
    ax.scatter(value,j,marker='o' if j==0 else 'D',s=28,
               facecolor='white' if j==0 else CHLORO,edgecolor=CHLORO,lw=1,zorder=2)
    ax.annotate(f'{value:.1f}°',(value,j),xytext=(-5 if j==0 else 5,0),textcoords='offset points',
                ha='right' if j==0 else 'left',fontsize=7.65,va='center',color=CHLORO,weight='bold')
ax.set(xlim=(0,48),ylim=(2.55,-.55),yticks=range(3),yticklabels=['para-Cl','para-Cl₂','para-Cl₄'],
       xticks=[0,10,20,30,40],xlabel='Largest calculated ligand fold (°)')
ax.spines['left'].set_visible(False)
ax.tick_params(axis='y',length=0,pad=4)
p.save('04_fold')
