"""Orthographic rendering from the deposited XYZ files. Coordinates and lengths are in Å."""
from itertools import combinations, product
from pathlib import Path
import re
import numpy as np
from matplotlib.colors import to_rgb

ROOT = Path(__file__).resolve().parents[2]
COL = dict(C='#5c6670', S='#e0a73d', V='#237e91', O='#ca5746', P='#d68150',
           N='#4a72a6', F='#63aeb5', Cl='#559567', Br='#995540', I='#885382',
           Mo='#7986a0', As='#a67d98', H='#ced7dd')
COV = dict(C=.76,S=1.05,V=1.53,O=.66,P=1.07,N=.71,F=.57,Cl=1.02,Br=1.20,I=1.39,
           Mo=1.54,As=1.19,H=.31)
RAD = dict(C=.33,S=.49,V=.60,O=.44,P=.47,N=.38,F=.43,Cl=.47,Br=.51,I=.56,
           Mo=.59,As=.49,H=.21)

def unit(v):
    return v / np.linalg.norm(v)

def xyz(path):
    lines = Path(path).read_text().splitlines()
    atoms = [line.split() for line in lines[2:] if line.strip()]
    assert len(atoms) == int(lines[0])
    cell = re.search(r'Lattice="([^"]+)"', lines[1])
    return (np.array([a[0] for a in atoms]), np.array([a[1:4] for a in atoms],float),
            np.fromstring(cell[1], sep=' ').reshape(3,3) if cell else None)

def topology(el, pos, cell=None):
    cutoff = np.array([COV[e] for e in el])
    dist = pos[:,None,:] - pos[None,:,:]
    if cell is not None:
        frac = dist @ np.linalg.inv(cell)
        dist = (frac-np.round(frac)) @ cell
    lens = np.linalg.norm(dist,axis=2)
    pairs = np.transpose(np.where(np.triu((lens < 1.17*(cutoff[:,None]+cutoff)) & (lens>.45),1)))
    return [(int(i),int(j)) for i,j in pairs]

def whole_crystal(el, pos, cell):
    pairs = topology(el,pos,cell)
    f = pos @ np.linalg.inv(cell)
    adj = [[] for _ in el]
    for i,j in pairs:
        adj[i].append(j)
        adj[j].append(i)
    visited = set()
    for i in range(len(f)):
        if i in visited:
            continue
        group, stack = [i], [i]
        visited.add(i)
        while stack:
            k = stack.pop()
            for j in adj[k]:
                if j not in visited:
                    f[j] -= np.round(f[j]-f[k])
                    visited.add(j)
                    stack.append(j)
                    group.append(j)
        f[group] -= np.floor(f[group].mean(axis=0))
    return f @ cell, pairs

def camera(x, up):
    x = unit(np.array(x,float))
    up = np.array(up,float)
    y = unit(up - x * (up @ x))
    return np.array([x,y,np.cross(x,y)]).T

def tilt(frame, deg):
    a = np.radians(deg)
    return frame @ np.array([[1,0,0],[0,np.cos(a),-np.sin(a)],[0,np.sin(a),np.cos(a)]])

def anion_frame(el, pos, elevation=52):
    v = pos[el=='V'][0] if 'V' in el else pos[el=='Mo'][0]
    o = min(pos[el=='O'],key=lambda x: np.linalg.norm(x-v))
    z = unit(o-v)
    heavy = pos[el!='H']-v
    inplane = heavy - (heavy @ z)[:,None]*z
    long = np.linalg.svd(inplane)[2][0]
    # Align the more strongly folded ligand to the right when possible.
    if el.tolist().count('S')>=8:
        try:
            _, center, _, _, _ = fold_frame(el,pos)
            if (center-v)@long<0:
                long=-long
        except ValueError:
            pass
    return tilt(camera(long,z),elevation)

def cation_frame(el,pos):
    center = pos[np.isin(el,['P','As','N'])][0]
    labels = ['I','Br','Cl','F','N']
    rare = [p for e,p in zip(el,pos) if e in labels and np.linalg.norm(p-center)>2.5]
    if rare:
        target = unit(rare[-1]-center)
    else:
        target = unit(max(pos[el=='C'],key=lambda p:np.linalg.norm(p-center))-center)
    c = pos[el=='C']-center
    n = np.linalg.svd(c - (c@target)[:,None]*target)[2][0]
    # Pick a rotation about the substituted arm that keeps all four aryls visible.
    # Compare projected interatomic separations only for atoms distant in 3D.
    local=pos[el!='H']-center
    distant=np.linalg.norm(local[:,None]-local[None,:],axis=2)>2.7
    best=-np.inf
    for az in np.arange(0,180,5):
        base=tilt(camera(target,n),az)
        for yaw in (-19,-9,9,19):
            a=np.radians(yaw)
            cand=base @ np.array([[np.cos(a),0,-np.sin(a)],[0,1,0],[np.sin(a),0,np.cos(a)]])
            xy=(local @ cand)[:,:2]
            ds=np.linalg.norm(xy[:,None]-xy[None,:],axis=2)[distant]
            score=-np.exp(-(ds/.66)**2).sum()
            if score>best:
                best=score
                frame=cand
    rot = np.radians(17)
    return frame @ np.array([[np.cos(rot),np.sin(rot),0],[-np.sin(rot),np.cos(rot),0],[0,0,1]])

def fold_frame(el,pos):
    v = pos[el=='V'][0]
    sulfurs = pos[(el=='S') & (np.linalg.norm(pos-v,axis=1)<2.7)]
    carbon=pos[el=='C']
    folds=[]
    for a,b in combinations(sulfurs,2):
        c,d=[min(carbon,key=lambda p:np.linalg.norm(p-s)) for s in (a,b)]
        if not 1.0<np.linalg.norm(c-d)<1.65:
            continue
        mid=(a+b)/2
        n1=unit(np.cross(a-v,b-v))
        n2=np.linalg.svd(np.array([a,b,c,d])-np.mean([a,b,c,d],axis=0))[2][-1]
        angle=np.degrees(np.arccos(np.clip(abs(n1@n2),0,1)))
        hinge=unit(b-a)
        x=unit(mid-v-((mid-v)@hinge)*hinge)
        y=unit(np.cross(hinge,x))
        if y@(pos[el=='O'][0]-v)<0:
            y=-y
        folds.append((angle,mid,camera(x,y),n1,n2))
    return max(folds,key=lambda r:r[0])

def draw(ax, el, pos, frame, *, pairs=None, cell=None, keep_h=False, scale=.86,
         ppm=100, limits=None, center=None):
    """Depth-buffer intersections with spheres and finite cylinders, then contact shading."""
    pairs = topology(el,pos) if pairs is None else pairs
    show = np.ones(len(el),bool) if keep_h else el!='H'
    proj = (pos - (np.zeros(3) if center is None else center)) @ frame
    corners = None
    if cell is not None:
        frac=np.array(list(product([0,1], repeat=3)))
        corners=(frac @ cell) @ frame
        for i,j in combinations(range(8),2):
            if np.abs(frac[i]-frac[j]).sum()==1:
                ax.plot(*corners[[i,j],:2].T,color='#879a9e',lw=.58,zorder=.1)
    extentpts=proj[show,:2] if corners is None else np.vstack((proj[show,:2],corners[:,:2]))
    if limits is None:
        lo=extentpts.min(axis=0)-.75
        hi=extentpts.max(axis=0)+.75
    else:
        lo=np.array([limits[0],limits[2]]); hi=np.array([limits[1],limits[3]])
    w,h=np.ceil((hi-lo)*ppm).astype(int)
    zbuf=np.full((h,w),-np.inf,dtype=float)
    rgb=np.ones((h,w,3))
    light=unit(np.array([-.38,.54,.75]))
    halfway=unit(light+[0,0,1])
    colors=np.array([to_rgb(COL[e]) for e in el])
    def tile(xy0,xy1):
        left,bottom=np.clip(np.floor((xy0-lo)*ppm).astype(int),[0,0],[w,h])
        right,top=np.clip(np.ceil((xy1-lo)*ppm).astype(int)+1,[0,0],[w,h])
        if right<=left or top<=bottom:
            return None
        yy,xx=np.mgrid[bottom:top,left:right]
        return (slice(bottom,top),slice(left,right)),lo[0]+(xx+.5)/ppm,lo[1]+(yy+.5)/ppm
    def paint(s,z,mask,nrm,color):
        take=mask & (z>zbuf[s])
        if not take.any(): return
        n=nrm[take]
        diffuse=np.maximum(0,n@light)
        spec=np.maximum(0,n@halfway)**38
        shade=.64+.36*diffuse
        c=color if color.ndim==1 else color[take]
        rgb[s][take]=np.clip(c*shade[:,None]+(.14*spec)[:,None],0,1)
        zbuf[s][take]=z[take]
    for i,j in pairs:
        if not (show[i] and show[j]):continue
        a,b=proj[[i,j]]
        r=.112*scale
        part=tile(np.minimum(a[:2],b[:2])-r,np.maximum(a[:2],b[:2])+r)
        if part is None:continue
        s,xx,yy=part
        axis=unit(b-a)
        den=1-axis[2]**2
        if den<1e-8:continue
        dx,dy=xx-a[0],yy-a[1]
        cross=dx*axis[0]+dy*axis[1]
        term=cross*axis[2]
        disc=term**2-den*(dx*dx+dy*dy-cross**2-r*r)
        dz=(term+np.sqrt(np.maximum(0,disc)))/den
        t=cross+dz*axis[2]
        normals=(np.stack([dx,dy,dz],axis=-1)-t[:,:,None]*axis)/r
        c=np.where((t<np.linalg.norm(b-a)/2)[:,:,None], colors[i], colors[j])
        c=.46*c+.54*np.array([.54,.58,.59])
        paint(s,a[2]+dz,(disc>=0)&(t>=0)&(t<=np.linalg.norm(b-a)),normals,c)
    for i in np.where(show)[0]:
        a=proj[i]; r=RAD[el[i]]*scale
        part=tile(a[:2]-r,a[:2]+r)
        if part is None:continue
        s,xx,yy=part
        dx,dy=xx-a[0],yy-a[1]
        discr=r*r-dx*dx-dy*dy
        dz=np.sqrt(np.maximum(discr,0))
        paint(s,a[2]+dz,discr>=0,np.stack([dx,dy,dz],axis=-1)/r,colors[i])
    seen=np.isfinite(zbuf)
    depth=np.where(seen,zbuf,-1e4)
    occ=np.zeros_like(depth)
    for ang in np.linspace(0,2*np.pi,8,endpoint=False):
        for rad in (.24,.48):
            dx,dy=np.rint(rad*ppm*np.array([np.cos(ang),np.sin(ang)])).astype(int)
            delta=np.roll(depth,(dy,dx),axis=(0,1))-depth
            occ+=np.clip(delta/(rad+1e-6),0,1)*np.exp(-np.abs(delta)/1.3)
    rgb*=1-.21*occ[:,:,None]/16
    out=np.dstack((np.rint(rgb*255).astype('uint8'),seen.astype('uint8')*255))
    ax.imshow(out,origin='lower',extent=[lo[0],lo[0]+w/ppm,lo[1],lo[1]+h/ppm],
              zorder=1,interpolation='antialiased',resample=True)
    ax.set(xlim=(lo[0],hi[0]),ylim=(lo[1],hi[1]),aspect='equal')
    ax.axis('off')
    return proj

def ion(ax,salt,kind,*,profile=False,**kw):
    path=ROOT/'structures'/'molecules'/f'{salt}_{kind}.xyz'
    el,pos,_=xyz(path)
    frame=anion_frame(el,pos) if 'anion' in kind else cation_frame(el,pos)
    if profile:
        _,_,frame,_,_=fold_frame(el,pos)
    draw(ax,el,pos,frame,**kw)
