"""Structures, prospective fold screen and row-matched lifetime atlas."""
import numpy as np
from matplotlib.colors import LinearSegmentedColormap, TwoSlopeNorm
from matplotlib.lines import Line2D
from matplotlib.patches import Rectangle
from matplotlib.cm import ScalarMappable
from geometry import molecule,cation_alignment,ring_paths,para_fragment
from structures import draw,anion_frame,COL
from si_methods import save_si
from plate import Plate,INK,MUTED
from make_figures import salts,NAMES,MARK,ACC,result,series,sigma,numeric,getdata

def chemical_series():
    p=Plate(92)
    p.panel(1,3,'a','Substitution at one ring site on the counterion')
    e,q,frame=cation_alignment('R5_pI')
    ax=p.axes(1,8,39,31)
    xy=draw(ax,e,q,frame,ppm=115)
    _,paths,j=ring_paths(e,q)
    ring=xy[paths[j],:2]
    center=ring.mean(0)
    ax.plot(*np.vstack([center+1.23*(ring-center),center+1.23*(ring[0]-center)]).T,ls=(0,(2.3,1.8)),c='#607278',lw=.68)
    p.text(20,43,'para-I cation',ha='center')
    p.line(45,9,45,40,color='#b8c4c7',lw=.5)
    for j,(k,elem) in enumerate([('SEED','H'),('R3_F','F'),('R4_pCl','Cl'),('R4_pBr','Br'),('R5_pI','I')]):
        x=49+j*26
        para_fragment(p.axes(x,11,25.5,27),k,elem)
        p.text(x+12.75,43,'H (parent)' if elem=='H' else elem,ha='center')
    p.panel(1,51,'b','Three edits to the spin-bearing anion')
    aligned=[]
    for k in ['SEED','R1_DMID_m1','R1_C3S5_m1','R1_C5H6S4']:
        e,q=molecule(k)
        aligned.append((e,q-q[e=='V'][0],anion_frame(e,q)))
    ext=np.vstack([((q@f)[e!='H'])[:,:2] for e,q,f in aligned])
    lo=ext.min(0)-.60;hi=ext.max(0)+.60
    names=['dmit (parent)','dmid (S → O)','C₃S₅ isomer','C₅H₆S₄']
    for j,((e,q,f),name) in enumerate(zip(aligned,names)):
        ax=p.axes(j*45+.5,56,44,22)
        projected=draw(ax,e,q,f,limits=(lo[0],hi[0],lo[1],hi[1]),ppm=120)
        if j in (0,1):
            # Circle the same outward-facing terminal atom in the parent and carbonyl structures.
            element='S' if j==0 else 'O'
            selected=np.flatnonzero(e==element)
            terminal=selected[np.argmax(projected[selected,0])]
            for edge,width in [('white',2.15), ('#394a53',.82)]:
                ax.scatter(*projected[terminal,:2],s=112,fc='none',ec=edge,lw=width,
                           zorder=5,clip_on=False)
        p.text(j*45+22.5,80,name,ha='center')
    for j,sym in enumerate(['V','O','S','C','P']):
        x=66+10*j
        p.line(x,87.5,x,87.5,marker='o',mfc=COL[sym],mec='none',ms=4)
        p.text(x+2.2,87.5,sym,fontsize=6.2)
    save_si(p,'S2_chemical_series')

def screen():
    p=Plate(129)
    p.panel(1,3,'a','From eleven counterions to two salt designs for DFT')
    from matplotlib.patches import FancyArrowPatch
    for x,title in [(3,'Clari generates packings'), (63,'UMA ranks by free energy'),
                    (123,'DFT for folds below 24°')]:
        p.text(x,14,title,fontsize=8.4,weight='bold',color='#5363a7')
    for x in (53.5,113.5):
        arrow=FancyArrowPatch((x/p.w,1-14/p.h),((x+7)/p.w,1-14/p.h),
                              transform=p.f.transFigure,arrowstyle='-|>',mutation_scale=7.5,
                              shrinkA=0,shrinkB=0,lw=.9,color='#c72c6a')
        p.f.add_artist(arrow)
    p.panel(1,24,'b','Lowest-energy packing per counterion')
    p.panel(95,24,'c','Estimated vs refined folds')
    p.panel(95,83,'d','Both shortlisted salts fall below the parent')
    ax=p.axes(23,36,59,75)
    rows=sorted(getdata('flat_ligand_screen'),key=lambda r:float(r['UMA_max_fold_deg']))
    calib=getdata('uma_vs_dft_fold_calibration');hit={'para-ethynyl':'R6_4CCH','meta-Br':'R6_mBr'}
    matched={r['salt_id']:float(r['DFT_max_fold_deg']) for r in calib}
    ax.axvspan(15,24,color='#e9ecf8',zorder=-1)
    ax.axvline(24,c='#747f9b',lw=.65,ls=(0,(2,2)))
    for i,row in enumerate(rows):
        x=float(row['UMA_max_fold_deg'])
        ax.scatter(x,i,s=22,facecolor='white',edgecolor='#65738a',lw=.85,zorder=3)
        if row['cation'] in hit:
            y=matched[hit[row['cation']]]
            ax.plot([x,y],[i,i],c='#747f98',lw=1.05)
            ax.scatter(y,i,s=23,c='#5363a7',marker='D',zorder=4)
    labels=[r['cation'].replace(' counterion','').replace(' on As core',' (As)').replace('NO2','NO₂').replace('PPN+','PPN⁺') for r in rows]
    ax.set(xlim=(15,50),ylim=(10.55,-.55),xticks=[20,30,40,50],yticks=range(11),yticklabels=labels,xlabel='Maximum fold (°)')
    ax.spines['left'].set_visible(False);ax.tick_params(axis='y',length=0)
    ax.text(24.6,-.9,'24° UMA cutoff',va='center',fontsize=6.15)
    handles=[Line2D([],[],ls='',marker='o',mfc='white',mec='#65738a',ms=3.6,label='UMA'),Line2D([],[],ls='',marker='D',c='#5363a7',ms=3.5,label='DFT')]
    p.f.legend(handles=handles,loc='center',bbox_to_anchor=(.285,.032),ncol=2,handletextpad=.2,columnspacing=1.2)
    ax=p.axes(111,34,34,31)
    ax.plot([12,46],[12,46],ls=(0,(2,2)),c='#9ba5a7',lw=.7)
    for r in calib:
        k=r['salt_id'];ax.scatter(float(r['UMA_max_fold_deg']),float(r['DFT_max_fold_deg']),marker='D' if k in hit.values() else 'o',s=17,c='#5363a7' if k in hit.values() else '#78888d',zorder=3)
    ax.set(xlim=(12,46),ylim=(12,46),xticks=[15,30,45],yticks=[15,30,45],xlabel='UMA fold (°)',ylabel='DFT fold (°)',aspect='equal')
    earlier=[r for r in calib if r['salt_id'] not in hit.values()]
    mae=np.mean([abs(float(r['UMA_max_fold_deg'])-float(r['DFT_max_fold_deg'])) for r in earlier])
    p.line(149,46,149,46,marker='o',mfc='#78888d',mec='none',ms=3.6)
    p.text(152,46,'Calibration (7)',fontsize=6)
    p.text(149,51,'Mean absolute error',fontsize=6)
    p.text(149,55,f'{mae:.1f}°',fontsize=6.3)
    p.line(149,62,149,62,marker='D',mfc='#5363a7',mec='none',ms=3.6)
    p.text(152,62,'Later salts (2)',fontsize=6)
    ax=p.axes(111,91,64,26)
    for k,r in salts.items():
        selected=k in hit.values()
        xy=(float(r['max_fold_deg']),result(k,20))
        ax.scatter(*xy,s=27 if selected else 17,marker='D' if selected else 'o',
                   facecolor='#5363a7' if selected else '#b7c0c4',ec='white',lw=.4,
                   zorder=4 if selected else 2)
        if selected:
            offset=(3,6) if k=='R6_4CCH' else (0,-9)
            ax.annotate(NAMES[k],xy,xytext=offset,textcoords='offset points',
                        fontsize=7.2,ha='left' if k=='R6_4CCH' else 'center',color=INK)
    ax.axhline(1,c='#747f90',ls=(0,(2,2)),lw=.7)
    ax.set(xlim=(12,42),ylim=(.37,1.27),xticks=[15,25,35],yticks=[.5,1],
           xlabel='DFT fold (°)',ylabel='Lifetime / parent at 20 cm⁻¹')
    save_si(p,'S5_packing_screen')

def matrix():
    p=Plate(152)
    p.panel(1,3,'a','Absolute lifetime in 17 models')
    p.panel(91,3,'b','Lifetime relative to the parent at each width')
    left,width=34,45
    heat_x,heat_w=100,77
    first=14;rh=5.9;gap=2.1
    keys=list(salts)
    cmap=LinearSegmentedColormap.from_list('relative',['#995b37','#f6f4ed','#267879'])
    norm=TwoSlopeNorm(1,vmin=.38,vmax=2.)
    parent=numeric(series('SEED'),'T1_us')
    levels=5.4
    current=None
    for i,k in enumerate(keys):
        r=int(salts[k]['round'])
        y=first+i*rh+gap*r
        if r!=current:
            if r:
                p.line(1,y-1.1,177,y-1.1,c='#c8d0d1',lw=.43)
                p.text(1,y+rh/2,f'R{r}',color=MUTED,fontsize=5.9)
            current=r
        p.text(left-2,y+rh/2,NAMES[k],ha='right',fontsize=6.3)
        ax=p.axes(left,y,width,rh)
        vals=numeric(series(k),'T1_us')
        ax.plot(sigma,parent,ls=(0,(2,1.6)),c='#8c989a',lw=.65)
        ax.plot(sigma,vals,c=ACC.get(k,'#435961'),lw=.92)
        ax.set(xlim=(2,30),ylim=(0,levels));ax.axis('off')
        h=p.axes(heat_x,y,heat_w,rh)
        ratios=np.array([result(k,v) for v in sigma])
        h.pcolormesh(np.arange(9)-.5,[-.5,.5],[ratios],cmap=cmap,norm=norm,shading='flat')
        for j in range(1,len(sigma)):h.axvline(j-.5,c='white',lw=.42)
        narrow=np.flatnonzero(np.isin(sigma,[3,5,7]))
        if (ratios[narrow]>=1.2).all():
            h.add_patch(Rectangle((narrow[0]-.48,-.46),len(narrow)-.04,.92,
                                  fill=False,edgecolor=INK,lw=.8,zorder=5))
        h.axis('off')
    bottom=y+rh
    for x in [2,10,20,30]:
        xx=left+(x-2)/28*width
        p.line(xx,bottom+.3,xx,bottom+1.3,lw=.52)
        p.text(xx,bottom+3.5,str(x),ha='center',fontsize=6.1)
    p.line(left,bottom+.3,left+width,bottom+.3,lw=.52)
    for j,width_value in enumerate(sigma):
        p.text(heat_x+(j+.5)*heat_w/len(sigma),bottom+3.5,f'{width_value:g}',ha='center',fontsize=6.1)
    p.text(left+width/2,bottom+8,'Vibrational linewidth, σ (cm⁻¹)',ha='center')
    p.text(heat_x+heat_w/2,bottom+8,'Vibrational linewidth, σ (cm⁻¹)',ha='center')
    # A vertical bar defines the amplitude of all individual traces.
    p.line(82,first+rh-5/levels*rh,82,first+rh,lw=.73)
    p.line(81.4,first+rh,82.6,first+rh,lw=.73)
    p.line(81.4,first+rh-5/levels*rh,82.6,first+rh-5/levels*rh,lw=.73)
    p.text(83,first+rh/2,'5 µs',fontsize=6.0)
    p.text(136,140.8,'Lifetime relative to parent',fontsize=7,ha='center')
    cb=p.f.colorbar(ScalarMappable(norm=norm,cmap=cmap),cax=p.axes(105,144.2,62,1.8),orientation='horizontal',ticks=[.4,1,1.5,2])
    cb.outline.set_visible(False);cb.ax.tick_params(length=1.6,pad=1)
    p.line(2,140,8,140,ls=(0,(2,1.6)),color='#8c989a',lw=.75)
    p.text(9.3,140,'Parent reference',fontsize=6.2)
    patch=Rectangle((34/p.w,1-141.4/p.h),5/p.w,2.8/p.h,fill=False,lw=.8,
                    edgecolor=INK,transform=p.f.transFigure)
    p.f.add_artist(patch)
    p.text(40.5,140,'≥1.2× parent at σ = 3, 5 and 7',fontsize=6.15)
    save_si(p,'S6_model_comparison')
