"""Matched cell views and linewidth-resolved phonon-pair contributions."""
import numpy as np
from plate import Plate,INK,MUTED
from geometry import adjacency, connected, crystal_data, draw_cell
from structures import anion_frame, draw
from make_figures import getdata,result,NAMES,MARK,ACC

p=Plate(190)
p.panel(1,3.6,'a','Crystal cells and one enlarged spin-bearing ion from each')
for x,k in [(1,'R5_pI'),(61,'SEED'),(121,'R4_pCl')]:
    ax=p.axes(x,12,58,50)
    count=draw_cell(ax,k,span=(29.6,26.5))
    p.text(x+29,8.9,f'{NAMES[k]}  ·  {count} '+('anion' if count==1 else 'anions'),
           ha='center',fontsize=8.1)
    if k=='R5_pI':
        xmin,_=ax.get_xlim();ymin,_=ax.get_ylim()
        ax.plot([xmin+1,xmin+6],[ymin+1.2]*2,c=INK,lw=1.05)
        ax.text(xmin+3.5,ymin+2.05,'5 Å',ha='center',fontsize=7.1)
    # Extract one complete anion from this very cell. Align to the same local
    # molecular axes so that packing orientation does not obscure the chemistry.
    elements,positions,_,bonds,_,_=crystal_data(k)
    v=int(np.flatnonzero(elements=='V')[0])
    group=sorted(connected(v,adjacency(bonds,len(elements))))
    e, q=elements[group],positions[group]-positions[v]
    draw(p.axes(x,63,58,19.4),e,q,anion_frame(e,q),limits=(-7.85,7.85,-3.2,2.05),ppm=138)
p.panel(1,94,'b','All three four-anion models fall below the parent')
p.text(4,101.6,'σ = 3 cm⁻¹',color=MUTED,fontsize=7.25)
ax=p.axes(20,110,58,22)
desc=getdata('mechanism_descriptors')
for row_index,sites in enumerate([1,2,4]):
    models=sorted([r for r in desc if int(r['V_per_cell'])==sites],key=lambda r:result(r['salt'],3))
    placed=[]
    for row in models:
        k=row['salt']
        value=result(k,3)
        offset=next(d for d in (0,-.18,.18,-.36,.36) if
                    all(abs(value-x)>.045 or abs(d-o)>.15 for x,o in placed))
        placed.append((value,offset))
        ax.scatter(value,row_index+offset,s=25,color=ACC.get(k,'#a6afb9'),
                   marker=MARK.get(k,'o'),edgecolors='white',linewidth=.45,zorder=3)
        if k=='R3_F':
            ax.annotate(NAMES[k],(value,row_index+offset),(-1.4,-4.8),textcoords='offset points',
                        color=ACC[k],ha='right',va='top',fontsize=7.2)
        if k in ('R5_pI','R4_pCl'):
            ax.annotate(NAMES[k],(value,row_index+offset),(3.6,0),textcoords='offset points',
                        color=ACC[k],va='center',fontsize=7.2)
ax.axvline(1,c='#8893a6',lw=.7,ls=(0,(2.5,2)),zorder=0)
ax.text(1,-.5,'Parent',ha='center',va='bottom',color=ACC['SEED'],fontsize=7.2,
        bbox=dict(facecolor='white',edgecolor='none',pad=.45))
ax.set(xlim=(.43,1.78),ylim=(2.54,-.72),yticks=[0,1,2],yticklabels=['1 anion','2 anions','4 anions'],
       xticks=[.5,1,1.5],xticklabels=['0.5×','1.0×','1.5×'],xlabel='Spin lifetime relative to parent')
ax.spines['left'].set_visible(False)
ax.tick_params(axis='y',length=0)

pairs={(r['salt_id'],int(r['sigma_cm1'])):r for r in getdata('pair_mismatch_decomposition') if r['sampling']=='dense'}
p.panel(88,94,'c','Nearly matched vibrations dominate in para-Cl')
p.text(91,101.6,'Pairs ≤1 cm⁻¹ apart at σ = 3 cm⁻¹',color=MUTED,fontsize=7.25)
ax=p.axes(111,109,59,23)
order=['R4_pCl','SEED','R3_F','R5_pI']
for index,k in enumerate(order):
    share=100*float(pairs[k,3]['share_mismatch_le_1cm1'])
    ax.barh(index,share,height=.47,color=ACC[k],label=NAMES[k])
    ax.annotate(f'{share:.0f}%',(share,index),(3.4,0),textcoords='offset points',
                va='center',fontsize=7.35,color=INK)
ax.set(xlim=(0,68),ylim=(3.55,-.6),xticks=[0,20,40,60],yticks=range(4),
       yticklabels=[NAMES[k] for k in order],xlabel='Share of total relaxation rate (%)')
ax.spines['left'].set_visible(False)
ax.tick_params(axis='y',length=0)

p.panel(1,148,'d','More widely separated vibrations reverse the iodine advantage')
p.text(4,155.3,'Iodine minus parent relaxation rate (10³ s⁻¹)',fontsize=7.35,color=MUTED)
def partition(salt,width):
    row=pairs[salt,width]
    total=1000/float(row['T1_us'])
    close=total*float(row['share_mismatch_le_10cm1'])
    return np.array([close,total-close,total])
for x,width,heading in [(36,3,'Longer lifetime'),(124,20,'Shorter lifetime')]:
    p.text(x+24.5,162.2,f'{heading} at {width} cm⁻¹',ha='center',fontsize=7.7,weight='bold')
    axis=p.axes(x,166,48.8,18)
    differences=partition('R5_pI',width)-partition('SEED',width)
    for i,delta in enumerate(differences):
        col=ACC['R5_pI'] if i==2 else '#8895af'
        axis.barh(i,delta,height=.39,color=col,zorder=2)
        if i==2 or abs(delta)<.5:
            label='≈0' if abs(delta)<.5 else f'{delta:+.0f}'.replace('-','−')
            side=-1 if i==2 and delta<0 else 1
            axis.annotate(label,(delta,i),xytext=(2.8*side,0),textcoords='offset points',
                          va='center',ha='left' if side==1 else 'right',fontsize=7.25,
                          weight='bold' if i==2 else 'normal',color=INK)
    axis.set(xlim=(-224,279),ylim=(2.54,-.55),yticks=range(3),
             yticklabels=['Pairs ≤10 cm⁻¹ apart','Pairs >10 cm⁻¹ apart','All pairs'],
             xticks=[-200,0,200],xticklabels=['−200','0','+200'])
    axis.axvline(0,color='#69788c',lw=.7,zorder=0)
    axis.spines['left'].set_visible(False)
    axis.tick_params(axis='y',length=0,pad=3.0,labelsize=7.0)
p.save('06_pair_mechanism')
