"""Nearest periodic halogen contact and a clear projection of its two molecular fragments."""
from dataclasses import dataclass
from functools import lru_cache
from itertools import product
import numpy as np
from geometry import connected, adjacency
from structures import ROOT, xyz, whole_crystal, draw, unit

@dataclass
class Contact:
    elements: np.ndarray
    positions: np.ndarray
    bonds: list
    frame: np.ndarray
    middle: np.ndarray
    carbon: int
    halogen: int
    sulfur: int
    vanadium: int
    distance: float
    angle: float

    def draw(self, ax, half_width=7.6, half_height=4.55, ppm=135):
        mx, my = self.middle
        projection = draw(ax, self.elements, self.positions, self.frame,
                          center=self.positions[self.halogen], pairs=self.bonds,
                          limits=(mx-half_width, mx+half_width, my-half_height, my+half_height),
                          ppm=ppm)
        ax.plot([.42, projection[self.sulfur,0]-.40], [0,0],
                ls=(0,(2.0,1.8)), color='#223039', lw=.9, zorder=2)
        return projection

@lru_cache(maxsize=2)
def closest_contact(salt, X):
    e,coords,cell=xyz(ROOT/f'structures/crystals/{salt}.extxyz')
    coords,bonds=whole_crystal(e,coords,cell);adj=adjacency(bonds,len(e))
    image_shifts=np.array(list(product(range(-1,2),repeat=3)))@cell
    def nearest():
        best=None
        for x in np.flatnonzero(e==X):
            for s in np.flatnonzero(e=='S'):
                lengths=np.linalg.norm(coords[s]+image_shifts-coords[x],axis=1)
                k=np.argmin(lengths)
                if best is None or lengths[k]<best[0]:
                    best=(lengths[k],x,s,image_shifts[k])
        return best
    dist,x,s,shift=nearest()
    c=next(a for a in adj[x] if e[a]=='C')
    # Only the ring bearing X and the ligand containing the contacted S.
    aryl=connected(c,[[i for i in n if e[i]=='C'] for n in adj])|{x}
    ligand=connected(s,[[i for i in n if e[i] in ('C','S')] for n in adj])
    v=next(a for i in ligand for a in adj[i] if e[a]=='V')
    o=next(a for a in adj[v] if e[a]=='O')
    ids=sorted(aryl|ligand|{v,o}); coords[sorted(ligand|{v,o})]+=shift
    theta=np.degrees(np.arccos(np.clip(unit(coords[s]-coords[x])@unit(coords[c]-coords[x]),-1,1)))
    assert (e[[*adj[s]]]=='V').any()==(X=='Br')
    # The context view may rotate about the contact, while the lower construction
    # uses the exact plane through all three atoms. Bond lists come from the crystal.
    local=coords[ids]-coords[x]
    d3=np.linalg.norm(local[:,None]-local[None,:],axis=2)
    mapped={idx:i for i,idx in enumerate(ids)}
    bond_pairs=[(mapped[a],mapped[b]) for a,b in bonds if a in mapped and b in mapped]
    fractions=np.linspace(.07,.93,11)
    samples=np.concatenate([local[a][None,:]+fractions[:,None]*(local[b]-local[a])[None,:]
                            for a,b in bond_pairs if x not in (ids[a],ids[b]) and s not in (ids[a],ids[b])])
    ligand_local=coords[sorted(ligand)]
    ligand_normal=np.linalg.svd(ligand_local-ligand_local.mean(0))[2][-1]
    aryl_points=coords[sorted(aryl-{x})]
    aryl_normal=np.linalg.svd(aryl_points-aryl_points.mean(0))[2][-1]
    dx=unit(coords[s]-coords[x]);best=-np.inf
    for i in range(4000):
        z=1-2*(i+.5)/4000; a=i*np.pi*(3-np.sqrt(5))
        n=np.array([np.sqrt(1-z*z)*np.cos(a),np.sqrt(1-z*z)*np.sin(a),z])
        if abs(dx@n)>.84:continue
        ex=unit(dx-(dx@n)*n);f=np.array([ex,np.cross(n,ex),n]).T
        xy=(local@f)[:,:2]; d2=np.linalg.norm(xy[:,None]-xy[None,:],axis=2)
        length=xy[mapped[s],0]
        points=(samples@f)[:,:2]
        inside=(points[:,0]>.32)&(points[:,0]<length-.34)
        near=np.exp(-(points[inside,1]/.49)**2).sum()
        area=np.linalg.svd(xy[[mapped[k] for k in aryl if e[k]=='C']]-xy[[mapped[k] for k in aryl if e[k]=='C']].mean(0))[1][-1]
        if abs(ligand_normal@n)<.24 or abs(aryl_normal@n)<.27:continue
        if xy[mapped[v],1]>xy[mapped[s],1]:continue
        near_x=np.linalg.norm(xy[[mapped[k] for k in ligand|{v,o} if k!=s]],axis=1).min()
        near_aryl=np.min([np.linalg.norm(xy[mapped[k]]-xy[mapped[l]]) for k in aryl for l in ligand|{v,o}])
        outer=np.maximum(0,.8-np.minimum(near_x,near_aryl))
        cost=.38*near+2*np.exp(-(d2[d3>2.65]/.72)**2).sum()
        clear=float(np.min(abs(points[inside,1]))) if np.any(inside) else 3.
        if near_x < 1.15 or clear < .65: continue
        ext=abs(aryl_normal@n)
        score=-cost+1.4*area+.75*length+3.0*abs(ligand_normal@n)-18*outer+4*min(near_x,1.8)+8*min(clear,1.0)+1.2*ext
        if score>best:best,context=score,f
    assert np.isfinite(best),f"No unobscured view of {salt}"
    ring=local@context
    middle=(ring[:,:2].min(0)+ring[:,:2].max(0))/2
    return Contact(e[ids],coords[ids],bond_pairs,context,middle,mapped[c],mapped[x],
                   mapped[s],mapped[v],float(dist),float(theta))
