"""The parent coordination geometry, fold construction and spin-relaxation target."""
import numpy as np
import json
from si_methods import save_si
from plate import Plate, INK, MUTED, PLANE_M, PLANE_L, ROOT
from geometry import fold_overview, fold_profile, draw_cell, crystal_data
from structures import COL
from make_figures import getdata

p=Plate(114)
p.panel(1,3,'a','Planes defining the parent ligand fold')
p.panel(95,3,'b','Fold viewed along the donor sulfur pair')
ax=p.axes(2,9,89,30)
q,(v,o,s1,s2,c1,c2)=fold_overview(ax,'SEED')
point=(q[s1,:2]+q[s2,:2])/2
ax.annotate('S···S hinge',point,xytext=(point[0]+1.6,point[1]+2.3),fontsize=6.5,
            ha='left',va='bottom',annotation_clip=False,arrowprops=dict(arrowstyle='-',color=INK,lw=.55,shrinkB=2))
for start,col,label in [(16,PLANE_M,'VS₂ plane'),(46,PLANE_L,'S₂C₂ plane')]:
    p.line(start,45,start+5,45,color=col,lw=2.1)
    p.text(start+6.5,45,label,fontsize=6.5)
profile=p.axes(100,8,73,32)
fold_profile(profile,'SEED')
profile.set_ylim(-1.15,3.15)
for j,symbol in enumerate(['V','O','S','C']):
    x=99+12*j
    p.line(x,45,x,45,marker='o',mfc=COL[symbol],mec='none',ms=4)
    p.text(x+2.4,45,symbol,fontsize=6.3)
p.panel(1,53,'c','Two vanadyl anions in the parent cell')
p.panel(95,53,'d','Target vibrations in the parent salt')
cell=p.axes(3,58,83,52)
draw_cell(cell,'SEED',True)
cell.images[0].set_alpha(.40)
elements,positions,_,_,_,frame=crystal_data('SEED')
vanadium=(positions[elements=='V']@frame)[:,:2]
for site,(x,y) in enumerate(sorted(vanadium,key=lambda point:-point[1]),1):
    cell.annotate(f'V{site}',(x,y),xytext=(24,3 if site==1 else -3),textcoords='offset points',
                  va='center',fontsize=6.4,color=INK,
                  arrowprops=dict(arrowstyle='-',color=MUTED,lw=.55,shrinkB=2))
ax=p.axes(111,66,59,27)
rows=[r for r in getdata('seed_rate_by_band') if float(r['sigma_cm1'])==10]
y=np.arange(len(rows))
values=[100*float(r['share_of_300K_rate']) for r in rows]
ax.barh(y,values,color='#cbd4d7',height=.54)
receipt=json.loads((ROOT/'preregistration'/'judge_receipt_R5_pI_rcpt-f0670a4fa30c.json').read_text())
family=receipt['details']['family']['parent']
target_fraction=100*family['rate_fraction']
ax.barh(3,target_fraction,color='#317887',height=.54)
ax.text(target_fraction/2,3,f'{target_fraction:.1f}%',ha='center',va='center',fontsize=6.3,color='white')
for legend_y,color,label in [(59,'#317887','Four V–S stretch / V=O tilt modes'),(63.5,'#cbd4d7','Other modes')]:
    p.line(110,legend_y,113.3,legend_y,color=color,lw=3.7,solid_capstyle='butt')
    p.text(115,legend_y,label,fontsize=7)
ax.set(yticks=y,yticklabels=['0–60','60–150','150–300','300–476'],xlim=(0,50),xticks=[0,20,40],
       xlabel='Share of total rate (%)',ylabel='Band (cm⁻¹)')
ax.invert_yaxis();ax.spines['left'].set_visible(False);ax.tick_params(axis='y',length=0)
save_si(p,'S1_parent_structure')
