"""Round-4 nearest-sulfur geometries and the controlled electronic fold scan."""
import numpy as np
from matplotlib.patches import Arc, Circle

from contact_geometry import closest_contact
from geometry import fold_profile
from make_figures import getdata, result, salts
from plate import INK, MUTED, Plate
from structures import camera, draw


def draw_packing_contact(ax, contact, halogen, v_offset):
    """Show the contacted ligand and the substituted ring at a fixed scale."""
    mx, my = contact.middle
    projection = draw(ax, contact.elements, contact.positions, contact.frame,
                      center=contact.positions[contact.halogen], pairs=contact.bonds,
                      limits=(mx - 6.25, mx + 6.25, my - 3.95, my + 3.95), ppm=145)
    sulfur = projection[contact.sulfur, :2]
    ax.plot([.34, sulfur[0] - .55], [0, 0], color=MUTED, lw=.65,
            linestyle=(0, (1.5, 2.0)), zorder=2)
    for colour, width in [('white', 1.65), (INK, .75)]:
        ax.add_patch(Circle(sulfur, .55, fill=False, edgecolor=colour,
                            linewidth=width, zorder=3))
    ax.annotate(halogen, projection[contact.halogen, :2], xytext=(-3, 5),
                textcoords='offset points', ha='right', va='bottom', fontsize=7)
    ax.annotate('V', projection[contact.vanadium, :2], xytext=v_offset,
                textcoords='offset points', ha='right' if v_offset[0] < 0 else 'left',
                va='top' if v_offset[1] < -2 else 'center', fontsize=7)
    return sulfur


def draw_contact_triplet(ax, contact, halogen):
    """Measure the approach in the C–X···S plane; the dotted line guides the eye."""
    distance, angle = contact.distance, contact.angle
    triplet = [contact.carbon, contact.halogen, contact.sulfur]
    positions = contact.positions[triplet] - contact.positions[contact.halogen]
    face_on = camera(positions[2], positions[0])
    projected = draw(ax, contact.elements[triplet], positions, face_on,
                     pairs=[(0, 1)], limits=(-3.12, 5.05, -1.0, 2.85), ppm=145, scale=.73)
    carbon = projected[0, :2]
    ax.plot([.43, distance - .39], [0, 0], color=MUTED,
            linestyle=(0, (1.0, 1.75)), linewidth=.90)
    ax.add_patch(Arc((0, 0), 2.15, 2.15, theta1=0, theta2=angle,
                     linewidth=.70, color=INK))
    halfway = np.deg2rad(angle / 2)
    ax.text(1.47 * np.cos(halfway), 1.47 * np.sin(halfway), f'{angle:.0f}°',
            ha='center', va='bottom', fontsize=7.1)
    ax.text(carbon[0] - .22, carbon[1] + .15, 'C', ha='right', va='bottom', fontsize=6.8)
    ax.text(0, -.43, halogen, ha='center', va='top', fontsize=6.8)
    ax.text(distance + .42, 0, 'S', va='center', fontsize=6.8)
    ax.text(distance * .61, -.44, f'{distance:.2f} Å', ha='center', va='top', fontsize=6.8)


def draw_fold_scan(ax):
    rows = getdata('fold_scan_upper_dpi')
    parent = next(row for row in rows if 'seed crystal geometry' in row['note'])
    angles, shifts = [], []
    for row in sorted(rows, key=lambda r:float(r['fold_deg'])):
        # The nominal 15° geometry and the 15.4° reference are the same calculation.
        if float(row['fold_deg']) == 15:
            continue
        angles.append(float(row['fold_deg']))
        shifts.append(float(row['upper_dpi_level_cm1']) - float(parent['upper_dpi_level_cm1']))
    reference_angle = float(parent['fold_deg'])
    ax.axhline(0, lw=.7, color='#9fa9b8', ls=(0,(3,2)))
    ax.plot(angles, shifts, '-o', color='#5363a7', lw=1.15, ms=3.5,
            markeredgecolor='white', markeredgewidth=.45)
    ax.plot(reference_angle, 0, 'o', color=INK, mfc='white', mew=.85, ms=4.5)
    ax.annotate('Parent', (reference_angle,0), xytext=(2,8),
                textcoords='offset points', fontsize=7.35, ha='center')
    ax.annotate(f'−{int(abs(shifts[-1]))}', (angles[-1],shifts[-1]),
                xytext=(-4,-1), textcoords='offset points', va='center',
                fontsize=7.45, weight='bold', ha='right', color='#5363a7')
    ax.set(xlim=(-1,37),ylim=(-925,180),xticks=[0,10,20,30,35],yticks=[-800,-400,0],
           xlabel='Ligand fold (°)',ylabel='Excitation energy shift (cm⁻¹)')


def make_figure():
    plate = Plate(79)
    for left, panel, salt, halogen, title, offset in [
        (0,'a','R4_pCl','Cl','Cl faces an outer-ring sulfur',(7,-1)),
        (60,'b','R4_pBr','Br','Br faces a V-bound sulfur',(-4,-5))]:
        plate.panel(left+1,3.3,panel,title)
        contact = closest_contact(salt,halogen)
        draw_packing_contact(plate.axes(left+1,7,58,35),contact,halogen,offset)
        fold_profile(plate.axes(left+1,41.5,58,21),salt)
        ratio=result(salt,20,sampling='gamma')
        plate.text(left+30,66,f'{ratio:.2f}× parent spin lifetime',fontsize=8.15,weight='bold',
                   ha='center',color='#5363a7')
    plate.panel(121,3.3,'c','Large folds lower excitation energy')
    draw_fold_scan(plate.axes(134.5,13,42,43))
    plate.text(90,75,'Would heavier iodine fold the ligand and shorten the spin lifetime at broad linewidth?',
               ha='center',fontsize=8.1,weight='bold',color='#ae275d')
    plate.save('03_campaign')


if __name__ in ('__figure__', '__main__'):
    make_figure()
