"""Coordinate-based views for the bend about S···S and comparisons between packings."""
from itertools import permutations, product
from functools import lru_cache
import numpy as np
from matplotlib.patches import Polygon, Arc
from structures import ROOT, COL, xyz, topology, whole_crystal, unit, camera, draw, fold_frame
from plate import INK, MUTED, PLANE_M, PLANE_L

def molecule(salt,kind="anion"):
    return xyz(ROOT/"structures"/"molecules"/f"{salt}_{kind}.xyz")[:2]

def connected(start,edges):
    selected={start}; pending=[start]
    while pending:
        i=pending.pop()
        for j in edges[i]:
            if j not in selected:
                pending.append(j);selected.add(j)
    return selected

def adjacency(pairs,n):
    neighbors=[[] for _ in range(n)]
    for a,b in pairs:
        neighbors[a].append(b); neighbors[b].append(a)
    return neighbors

def fold_atoms(salt):
    e,p=molecule(salt)
    angle,mid,frame,_,n2=fold_frame(e,p)
    v=int(np.flatnonzero(e=='V')[0])
    o=int(np.flatnonzero(e=='O')[0])
    donors=np.flatnonzero((e=='S') & (np.linalg.norm(p-p[v],axis=1)<2.7))
    s1,s2=sorted(donors,key=lambda i:np.linalg.norm(p[i]-mid))[:2]
    ci=np.flatnonzero(e=='C')
    cs=[ci[np.argmin(np.linalg.norm(p[ci]-p[i],axis=1))] for i in (s1,s2)]
    assert abs(np.linalg.norm(p[cs[0]]-p[cs[1]])-1.36)<.22
    adj=adjacency(topology(e,p),len(p))
    without_v=[[j for j in n if j!=v] for n in adj]
    ids=sorted(connected(s1,without_v)|{v,o})
    return e,p,angle,mid,frame,(v,o,s1,s2,*cs),ids

def camera_oblique(frame,elevation=42,azimuth=-23):
    # Rotate away from the hinge axis by the same angles in each structure.
    a,b=np.radians([elevation,azimuth])
    rx=np.array([[1,0,0],[0,np.cos(a),-np.sin(a)],[0,np.sin(a),np.cos(a)]])
    ry=np.array([[np.cos(b),0,np.sin(b)],[0,1,0],[-np.sin(b),0,np.cos(b)]])
    return frame@rx@ry

def fold_overview(ax,salt):
    e,p,angle,mid,base,indices,_=fold_atoms(salt)
    v,o,s1,s2,c1,c2=indices
    frame=camera_oblique(base,52,-18)
    proj=draw(ax,e,p,frame,center=mid,ppm=128,scale=.83)
    # Extend both reference surfaces slightly beyond their defining atoms.
    for ids,col in [([v,s1,s2],PLANE_M),([s1,c1,c2,s2],PLANE_L)]:
        xy=proj[ids,:2];xy=xy.mean(axis=0)+1.26*(xy-xy.mean(axis=0))
        ax.add_patch(Polygon(xy,fc=col+'41',ec=col,lw=.8,zorder=.8))
    h=proj[[s1,s2],:2];u=unit(h[1]-h[0]);h=np.array([h[0]-.38*u,h[1]+.38*u])
    ax.plot(*h.T,color=INK,ls=(0,(2,1.8)),lw=.85,zorder=2)
    return proj,indices

def fold_profile(ax,salt):
    e,p,angle,mid,frame,_,ids=fold_atoms(salt)
    # Orthographic view along the coordinating S pair. Higher fold is on the right.
    rad=np.deg2rad(angle)
    end=7.45
    x0,x1,y0,y1=-3.35,8.80,-1.55,5.95
    draw(ax,e[ids],p[ids],frame,center=mid,ppm=127,scale=.79,limits=(x0,x1,y0,y1))
    # Traces and the exterior angular dimension share a single origin.
    ax.plot([-2.5,end+.3],[0,0],color=PLANE_M,lw=.83,ls=(0,(3,1.8)),zorder=.8)
    ax.plot([0,end*np.cos(rad)],[0,end*np.sin(rad)],color=PLANE_L,lw=.9,zorder=.8)
    r=6.35
    ax.add_patch(Arc((0,0),2*r,2*r,theta1=0,theta2=angle,color=INK,lw=.86,zorder=3))
    for a in [0,rad]:
        ax.plot([(r-.17)*np.cos(a),(r+.16)*np.cos(a)],[(r-.17)*np.sin(a),(r+.16)*np.sin(a)],lw=.73,c=INK)
    ax.text((r+.35)*np.cos(rad/2),(r+.35)*np.sin(rad/2),f"{angle:.1f}°",ha="left",va="center",
            fontsize=7,weight="bold",color=INK)
    return angle

def crystal_data(salt):
    e,p,cell=xyz(ROOT/f"structures/crystals/{salt}.extxyz")
    p,pairs=whole_crystal(e,p,cell)
    adj=adjacency(pairs,len(e))
    groups=[];unseen=set(range(len(p)))
    while unseen:
        group=sorted(connected(min(unseen),adj));groups.append(group);unseen-=set(group)
    v=np.flatnonzero(e=='V')
    # The cell origin is arbitrary. Choose an origin maximizing clearance of the V
    # sites from each pair of opposite faces and wrap whole molecules by their centre.
    frac=p@np.linalg.inv(cell)
    shift=[]
    for dim in range(3):
        options=np.linspace(0,1,1000,endpoint=False)
        clearance=np.minimum((frac[v,dim,None]+options)%1,1-(frac[v,dim,None]+options)%1).min(axis=0)
        shift.append(options[np.argmax(clearance)])
    frac+=shift
    active=[]
    for g in groups:
        vsite=[i for i in g if e[i]=='V']
        anchor=frac[vsite[0]] if vsite else np.mean(frac[g],axis=0)
        frac[g]-=np.floor(anchor)
        if vsite:active.extend(g)
    p=frac@cell
    # Same crystallographic viewing convention for all cells: a principally horizontal,
    # c upward and a small oblique contribution from b.
    a,b,c=map(unit,cell)
    frame=camera(a-.34*b,c+.29*b)
    return e,p,cell,pairs,sorted(active),frame

def draw_cell(ax,salt,show_cations=False,span=None):
    e,p,cell,pairs,active,frame=crystal_data(salt)
    corners=np.array(list(product([0,1],repeat=3)))@cell@frame
    xx=np.vstack((corners[:,:2],(p[active]@frame)[:,:2]))
    if show_cations:xx=np.vstack((xx,(p[e!='H']@frame)[:,:2]))
    mid=(xx.max(0)+xx.min(0))/2
    dx,dy=(np.ptp(xx,axis=0)/2+.95) if span is None else np.asarray(span)/2
    lo=(mid[0]-dx,mid[0]+dx,mid[1]-dy,mid[1]+dy)
    if show_cations:
        ids=np.setdiff1d(np.arange(len(e)),active)
        local={j:i for i,j in enumerate(ids)}
        bonds=[(local[i],local[j]) for i,j in pairs if i in local and j in local]
        draw(ax,e[ids],p[ids],frame,pairs=bonds,limits=lo,ppm=80,scale=.87)
        ax.images[-1].set_alpha(.26)
        ax.images[-1].set_zorder(.25)
    local={j:i for i,j in enumerate(active)}
    bonds=[(local[i],local[j]) for i,j in pairs if i in local and j in local]
    draw(ax,e[active],p[active],frame,pairs=bonds,cell=cell,limits=lo,ppm=80,scale=.87)
    return len(np.flatnonzero(e=='V'))

def ring_paths(e,p):
    graph=adjacency(topology(e,p),len(p))
    ip=int(np.flatnonzero(e=='P')[0]);paths=[]
    for first in graph[ip]:
        if e[first]!='C':continue
        nxt=sorted(j for j in graph[first] if e[j]=='C')[0]
        path=[first,nxt]
        while len(path)<6:
            path.append(next(j for j in graph[path[-1]] if e[j]=='C' and j not in path))
        paths.append(path)
    assert len(paths)==4
    sub=np.flatnonzero(np.isin(e,['F','Cl','Br','I']))
    tagged=next((j for j,r in enumerate(paths) if len(sub) and r[3] in graph[sub[0]]),None)
    return ip,paths,tagged

def para_fragment(ax,salt,substituent):
    """Face-on view of the edited P–aryl–X branch at a fixed magnification."""
    e,q=molecule(salt,'cation')
    ip,rings,tag=ring_paths(e,q)
    ring=rings[0 if tag is None else tag]
    graph=adjacency(topology(e,q),len(e))
    end=next(i for i in graph[ring[3]] if e[i]==substituent)
    ids=[ip,*ring,end]
    points=q[ring]
    axis=points[3]-points[0]
    normal=np.linalg.svd(points-points.mean(0))[2][-1]
    frame=camera(axis,np.cross(normal,axis))
    return draw(ax,e[ids],q[ids],frame,center=points.mean(0),
                limits=(-4.05,4.6,-2.25,2.25),keep_h=True,ppm=128)

@lru_cache(maxsize=None)
def registered_cation(salt):
    re,rp=molecule('R5_pI','cation');ri,rr,rt=ring_paths(re,rp)
    e,p=molecule(salt,'cation');ip,rings,sub=ring_paths(e,p)
    order=[rt]+[i for i in range(4) if i!=rt];ref=rp[[k for i in order for k in rr[i]]]-rp[ri]
    best=np.inf
    for perm in permutations(range(4)):
        if sub is not None and perm[0]!=sub:continue
        for flips in product([False,True],repeat=4):
            idx=[]
            for j,flip in zip(perm,flips):
                ring=rings[j];idx.extend([ring[0],*ring[:0:-1]] if flip else ring)
            q=p[idx]-p[ip];u,_,vt=np.linalg.svd(q.T@ref)
            d=np.eye(3);d[2,2]=np.sign(np.linalg.det(u@vt));rot=u@d@vt
            err=np.mean((q@rot-ref)**2)
            if err<best:best=err;bestrot=rot
    return e,(p-p[ip])@bestrot

@lru_cache(maxsize=1)
def common_cation_view():
    # All five conformers contribute to the choice of camera. Identify equivalent
    # unsubstituted rings by the para carbon closest to the target reference arm.
    e0,p0=registered_cation('R5_pI')
    _,rings0,tag0=ring_paths(e0,p0)
    axis=unit(p0[rings0[tag0][3]])
    scenes=[]
    for salt in ('SEED','R3_F','R4_pCl','R4_pBr','R5_pI'):
        e,p=registered_cation(salt)
        _,rings,tag=ring_paths(e,p)
        ends=np.array([p[r[3]] for r in rings])
        if tag is None:tag=int(np.argmax(ends@axis))
        normals=np.array([np.linalg.svd(p[r]-p[r].mean(0))[2][-1] for r in rings])
        atoms=p[e!='H']
        distances=np.linalg.norm(atoms[:,None]-atoms[None,:],axis=2)
        scenes.append((ends,normals,tag,atoms,distances>2.7))
    best=-np.inf
    for j in range(3200):
        z=1-2*(j+.5)/3200
        a=j*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(n@axis)>.52:continue
        x=unit(axis-n*(n@axis));f=np.array([x,np.cross(n,x),n]).T
        scores=[];faces=[];all_faces=[]
        for ends,normals,tag,atoms,distant in scenes:
            arms=(ends@f)[:,:2]
            angles=np.sort(np.arctan2(arms[:,1],arms[:,0]))
            sep=np.diff(np.r_[angles,angles[0]+2*np.pi]).min()
            xy=(atoms@f)[:,:2]
            d2=np.linalg.norm(xy[:,None]-xy[None,:],axis=2)
            face=np.abs(normals@n)
            faces.append(face[tag]);all_faces.extend(face)
            scores.append(9*sep+4*face.min()+2*face[tag]-.43*np.exp(-(d2[distant]/.7)**2).sum())
        score=.40*min(scores)+.60*np.mean(scores)+3.7*min(faces)+10*np.quantile(all_faces,.15)+3*min(all_faces)
        if score>best:best=score;frame=f
    a=np.radians(14)
    return frame@np.array([[np.cos(a),np.sin(a),0],[-np.sin(a),np.cos(a),0],[0,0,1]])

def cation_alignment(salt):
    elements,coords=registered_cation(salt)
    return elements,coords,common_cation_view()
