"""Six rounds of salt design. Arrows follow the decisions, including the parallel screen."""
import numpy as np
from matplotlib.lines import Line2D
from matplotlib.patches import FancyArrowPatch, FancyBboxPatch
from matplotlib.transforms import Affine2D
from contact_geometry import closest_contact
from contacts import draw_packing_contact
from geometry import cation_alignment, molecule
from make_figures import getdata, result, salts
from plate import Plate
from structures import anion_frame, draw, ion

p = Plate(156)
ink, muted = '#192638', '#4f5c71'
pink, indigo = '#c72c6a', '#5363a7'
pale, border = '#f5f6fa', '#d9dee9'
mm = Affine2D().scale(1 / p.w, -1 / p.h).translate(0, 1) + p.f.transFigure
layers = {}
completed = {}
for row in getdata('salts'):
    design = row['salt_id'].removesuffix('_m1').removesuffix('_m2')
    completed.setdefault(int(row['round']),set()).add(design)
# The two gated chlorinated salts reached DFT but have no lifetime entry.
counts = {r:len(completed[r]) + (2 if r == 5 else 0) for r in range(1,7)}
assert sum(counts.values()) == 16
names = {1:'Weaken the V–S vibration', 2:'Replace the counterion', 3:'Change one ring site',
         4:'Compare heavier halogens', 5:'Test iodine at any ligand fold', 6:'Screen for flatter packings'}


def group(r):
    return (f'Round {r} · {names[r]}',)


def tag(artist, path):
    key = f'part-{len(layers)}'
    artist.set_gid(key)
    layers[key] = path
    return artist


def text(path, x, y, s, size=7.4, color=ink, bold=False, align='left'):
    return tag(p.text(x,y,s,fontsize=size,color=color,weight='bold' if bold else 'normal',
                      ha=align,zorder=5), path)


def box(path,x,y,w,h,fill='white',stroke=border):
    patch=FancyBboxPatch((x,y),w,h,boxstyle='round,pad=0,rounding_size=1.8',
                         transform=mm,facecolor=fill,edgecolor=stroke,lw=.7,zorder=-1)
    p.f.add_artist(tag(patch,path))


def arrow(name, coords, tip=True):
    path=('Decision arrows',name)
    x,y=zip(*coords)
    p.f.add_artist(tag(Line2D(x,y,transform=mm,color=pink,lw=.86,
                             solid_capstyle='butt',solid_joinstyle='round'),path))
    if tip:
        p.f.add_artist(tag(FancyArrowPatch(*coords[-2:],transform=mm,arrowstyle='-|>',
                                           shrinkA=0,shrinkB=0,mutation_scale=8.2,
                                           linewidth=.75,color=pink),path))


def heading(r,x,y):
    path=group(r)+('Question',)
    text(path,x,y,f'Round {r}  ·  {counts[r]} designs',7.65,pink)
    text(path,x,y+5.3,names[r],8.8,bold=True)


def view(path,x,y,w,h):
    return tag(p.axes(x,y,w,h),path)


def cation(ax, salt, symbol):
    elements,positions,frame=cation_alignment(salt)
    projected=draw(ax,elements,positions,frame,ppm=145)
    i=np.flatnonzero(elements==symbol)[0]
    ax.annotate(symbol,projected[i,:2],xytext=(3,3),textcoords='offset points',fontsize=7.5)


text(('Heading',),1,3.5,'How the agents reached the iodine test',10,bold=True)
text(('Heading',),179,3.5,f'Six rounds  ·  {sum(counts.values())} salt designs',7.5,muted,align='right')

for r,left in [(1,1),(2,63),(3,125)]:
    box(group(r)+('Background',),left,9,54,44)
    heading(r,left+3,13.7)
e,q=molecule('R1_DMID_m1')
ax=view(group(1)+('Carbonyl ligand',),3,21.2,49,24)
projected=draw(ax,e,q,anion_frame(e,q),ppm=145)
oxygen=max(np.flatnonzero(e=='O'),key=lambda i:projected[i,0])
ax.annotate('O',projected[oxygen,:2],xytext=(3.2,2),textcoords='offset points',fontsize=7.5)
ion(view(group(2)+('Tetraethylammonium',),64,21,24,24),'R2_NEt4','cation',ppm=145)
ion(view(group(2)+('Tetraphenylarsonium',),88.5,20.6,26.5,25),'R2_AsPh4','cation',ppm=145)
cation(view(group(3)+('para-F',),128,20.8,46,24.6),'R3_F','F')
for r,left,s in [(1,4,'Other vibrations offset the gain.'),(2,66,'Both swaps folded the ligand.'),
                 (3,128,'Fluorine extended the lifetime.')]:
    text(group(r)+('Result',),left,48.8,s,7.85,indigo)
arrow('Ligand changes to counterion exchanges',[(55,48.8),(59,48.8),(59,18.9),(63,18.9)])
arrow('Counterion exchanges to a single site',[(117,48.8),(121,48.8),(121,18.9),(125,18.9)])
arrow('Fluorine to the heavier halogens',[(152,53),(152,56.2),(90,56.2),(90,59.5)])

box(group(4)+('Background',),1,59.5,178,36.5,pale)
text(group(4)+('Question',),4,64,f'Round 4  ·  {counts[4]} designs',7.65,pink)
text(group(4)+('Question',),33,64,names[4],8.8,bold=True)
text(group(4)+('Readout',),175.5,64,'Linewidth 20 cm⁻¹',7.15,muted,align='right')
for x,salt,symbol,site,offset in [(2,'R4_pCl','Cl','Outer-ring sulfur',(6,-1)),
                                  (91,'R4_pBr','Br','V-bound sulfur',(-4,-5))]:
    path=group(4)+(f'para-{symbol}',)
    ax=view(path+('Crystal contact',),x,67.2,50,29)
    draw_packing_contact(ax,closest_contact(salt,symbol),symbol,offset)
    text(path,x+51,72,'para-'+symbol,8.35,bold=True)
    text(path,x+51,78,site,7.65)
    fold=float(salts[salt]['max_fold_deg'])
    ratio=result(salt,20,sampling='gamma')
    text(path,x+51,85,f'{fold:.1f}° fold',7.5)
    text(path,x+51,90.3,f'{ratio:.2f}× parent lifetime',7.6,indigo,True)

# Both branches arose from round 4. The screen began before the iodine result.
arrow('Fold hypothesis',[(90,96),(90,103)],False)
arrow('Test iodine even if folded',[(90,103),(47,103),(47,112)])
arrow('Select flatter predicted packings',[(90,103),(140.5,103),(140.5,112)])

box(group(5)+('Background',),1,112,94,42.5)
box(group(6)+('Background',),99,112,80,42.5)
heading(5,4,116.5)
heading(6,102,116.5)
cation(view(group(5)+('para-I',),2.8,124.2,33.5,27.7),'R5_pI','I')
text(group(5)+('Forecast and outcome',),38,131.4,'Broad lines',7.65,muted)
text(group(5)+('Forecast and outcome',),57,131.4,'Shorter, as forecast',7.5,indigo,True)
text(group(5)+('Forecast and outcome',),38,139.4,'Narrow lines',7.65,muted)
text(group(5)+('Forecast and outcome',),57,139.4,'Unexpected gain',7.5,indigo,True)
for x,salt,label in [(103,'R6_mBr','meta-Br'),(139,'R6_4CCH','para-ethynyl')]:
    ax=view(group(6)+(label,),x,123.5,33,17.4)
    ion(ax,salt,'cation',ppm=145)
    text(group(6)+(label,),x+16.5,142.1,label,7.25,muted,align='center')
text(group(6)+('Screen results',),102,150.1,'11 screened  →  2 calculated  →  0 met target',7.7,indigo,True)

p.save_layered_svg('02_round_path',layers)
p.save('02_round_path')
