"""Write the figure specs of the cyclodextrin page from the saved calculations.

    python cyclodextrin-figures.py --results ../results/cyclodextrin --models ../models/cyclodextrin \
        --work cd-analysis --figures ../../figures/cyclodextrin
"""

import argparse
import json
from pathlib import Path

import numpy as np
from scipy.spatial import cKDTree

from atomli.io import read
from atomli.visualize import FieldViewer, Viewer, plot

HOST, GUEST_COLOR, GUEST_COLOR_NAME = "#b9c0cb", "#d74737", "guest"
HOST_ATOMS = 147
LEGEND = {HOST: "host (β-cyclodextrin)", GUEST_COLOR: "guest (thymol)"}


def two_tone(atoms, guest_color=GUEST_COLOR):
    return [HOST if i < HOST_ATOMS else guest_color for i in range(len(atoms))]


STYLE = {"labels": False}


def cavity_axes(atoms, side=False):
    """Centre, view axis and up vector of the host ring: the smallest-variance principal axis is the cavity axis."""
    host = atoms.get_positions()[:HOST_ATOMS]
    centre = host.mean(axis=0)
    _, vectors = np.linalg.eigh(np.cov((host - centre).T))
    if side:
        return centre, vectors[:, 1], vectors[:, 0]
    return centre, vectors[:, 0], vectors[:, 2]


def camera(atoms, focus=None, distance=42.0, zoom=0.62, side=False, lift=0.8):
    """Camera looking down the cavity axis (or from the side) at the centroid of `focus` atoms."""
    centre, axis, up = cavity_axes(atoms, side)
    target = centre if focus is None else atoms.get_positions()[focus].mean(axis=0)
    target = target - up * lift  # moves the model up on screen, clear of the legend
    return {"position": (target + axis * distance).tolist(), "target": target.tolist(), "up": up.tolist(), "zoom": zoom}


def make_viewer(atoms, colors, legend, height=460, **look):
    viewer = Viewer([atoms], height=height, look={"atom_colors": colors, "color_legend": legend, **STYLE, **look})
    viewer.set_camera(**camera(atoms))
    return viewer


def frame_camera(viewer, atoms, focus, distance=42.0, side=False, zoom=0.9):
    """Give a field viewer a cavity-axis or side view, centred on the `focus` atoms of the full complex."""
    view = camera(atoms, focus, distance, zoom, side)
    original = viewer.to_snapshot
    def snapshot():
        data = original()
        data["camera"] = {"type": "perspective", **view}
        return data
    viewer.to_snapshot = snapshot
    return viewer


def local_names(symbols):
    return [f"{s}{k + 1}" for k, s in enumerate(symbols[HOST_ATOMS:])]


def pose_plot(results, out):
    records = json.loads((results / "poses.json").read_text())
    traces = []
    for guest, color in (("thymol", "#2266cc"), ("carvacrol", "#dc7c1b")):
        rows = [r for r in records if r["guest"] == guest]
        best = min(range(len(rows)), key=lambda k: rows[k]["binding_energy_ev"])
        traces.append({
            "type": "scatter", "mode": "markers", "name": guest.capitalize(),
            "x": [r["pose"] + (-0.06 if guest == "thymol" else 0.06) for r in rows], "y": [r["binding_energy_ev"] for r in rows],
            "customdata": [r["pose"] for r in rows],
            "marker": {"color": color, "size": [14 if k == best else 9 for k in range(len(rows))],
                       "symbol": ["diamond" if k == best else "circle" for k in range(len(rows))]},
            "hovertemplate": f"{guest} pose %{{customdata}}<br>%{{y:.3f}} eV<extra></extra>",
        })
    figure = {"data": traces, "layout": {
        "xaxis": {"title": {"text": "Starting orientation (pose index)"}, "tickvals": [0, 1, 2, 3], "range": [-0.4, 3.4]},
        "yaxis": {"title": {"text": "Binding energy (eV)"}, "zeroline": True},
        "legend": {"orientation": "h", "x": 0.5, "xanchor": "center", "y": -0.28},
        "margin": {"l": 70, "r": 20, "t": 20, "b": 100}}}
    plot.plotly(figure).write_spec(out / "cyclodextrin-poses.json")


def contact_viewers(results, out, guests):
    for guest, pose, legend_name in guests:
        atoms = read(results / f"{guest}-{pose}.xyz")
        atoms.set_pbc(False)
        legend = {HOST: LEGEND[HOST], GUEST_COLOR: f"guest ({legend_name})"}
        viewer = make_viewer(atoms, two_tone(atoms), legend, height=440)
        recognition = json.loads((results / "recognition.json").read_text())[guest]
        for bond in recognition["hydrogen_bonds"]:
            viewer.add_distance(bond["hydrogen"], bond["acceptor"], label=f"H···O {bond['ha_angstrom']:.3f} Å")
        viewer.write_spec(out / f"cyclodextrin-{guest}.json", structure_path=out / f"cyclodextrin-{guest}.extxyz",
                          structure_url=f"/figures/cyclodextrin/cyclodextrin-{guest}.extxyz")


def start_viewer(models, out):
    atoms = read(models / "thymol-start-0.xyz")
    atoms.set_pbc(False)
    viewer = make_viewer(atoms, two_tone(atoms), LEGEND, height=460)
    viewer.write_spec(out / "cyclodextrin-start.json", structure_path=out / "cyclodextrin-start.extxyz",
                      structure_url="/figures/cyclodextrin/cyclodextrin-start.extxyz")


def fukui_figures(results_json, atoms, out):
    symbols = results_json["symbols"][HOST_ATOMS:]
    names = [f"{s}{k + 1}" for k, s in enumerate(symbols)]
    plus, minus = results_json["fukui_guest"]["plus"], results_json["fukui_guest"]["minus"]
    figure = {"data": [
        {"type": "bar", "name": "f⁻ (electrophilic attack)", "x": names, "y": minus, "marker": {"color": "#2266cc"}},
        {"type": "bar", "name": "f⁺ (nucleophilic attack)", "x": names, "y": plus, "marker": {"color": "#dc4b4b"}}],
        "layout": {"barmode": "group",
                   "xaxis": {"title": {"text": "Guest atom (1-based index; O is the hydroxyl oxygen)"}, "tickangle": -60},
                   "yaxis": {"title": {"text": "Condensed Fukui function (e)"}},
                   "legend": {"orientation": "h", "x": 0.5, "xanchor": "center", "y": -0.45},
                   "margin": {"l": 70, "r": 20, "t": 20, "b": 150}}}
    plot.plotly(figure).write_spec(out / "cyclodextrin-fukui-bars.json")
    guest_only = atoms[HOST_ATOMS:]
    for label, values, palette in (("minus", minus, "f⁻"), ("plus", plus, "f⁺")):
        values = np.asarray(values)
        top = values.max()
        bins = [("#d1352b", f"{palette} ≥ 50% of the maximum"), ("#f0a040", f"{palette} 20% to 50% of the maximum"),
                ("#6aa7d8", f"{palette} < 20% of the maximum")]
        colors = []
        for value in values:
            colors.append(bins[0][0] if value >= 0.5 * top else bins[1][0] if value >= 0.2 * top else bins[2][0])
        legend = {c: t for c, t in bins}
        viewer = Viewer([guest_only], height=420, look={"atom_colors": colors, "color_legend": legend, **STYLE})
        g = guest_only.get_positions()
        _, vec = np.linalg.eigh(np.cov((g - g.mean(axis=0)).T))
        viewer.set_camera(position=(g.mean(axis=0) - vec[:, 2] * 0.8 + vec[:, 0] * 27).tolist(), target=(g.mean(axis=0) - vec[:, 2] * 0.8).tolist(),
                          up=vec[:, 2].tolist(), zoom=0.62)
        viewer.set_tags({k: f"{names[k]} {v:.2f}" for k, v in enumerate(values) if v >= 0.1})
        viewer.write_spec(out / f"cyclodextrin-fukui-{label}.json", structure_path=out / f"cyclodextrin-fukui-{label}.extxyz",
                          structure_url=f"/figures/cyclodextrin/cyclodextrin-fukui-{label}.extxyz")


def field_dict(kind, values, origin, axes, unit):
    return {"kind": kind, "length_unit": "angstrom", "shape": list(values.shape), "origin": list(map(float, origin)),
            "axes": [list(map(float, a)) for a in axes], "values": values.astype(np.float32),
            "value_unit": unit, "representation": "all-electron PBE/def2-SVP"}


def interface_mask(data, tolerance=0.4, reach=3.5, inside=1.0, guest_reach=2.0):
    """Grid points lying between a guest atom and a host atom, not inside either molecule's own bonds.

    A point qualifies when its nearest guest atom g and nearest host atom h satisfy
    |p-g| + |p-h| < |g-h| + tolerance, so it sits near the g-h segment, the guest atom is within `guest_reach` and the host atom within `reach`, and both are at least `inside` angstrom from an atom (outside the bonded regions).
    """
    positions = data["positions"]
    host_pos, guest_pos = positions[:HOST_ATOMS], positions[HOST_ATOMS:]
    shape = data["rdg"].shape
    spacing = float(data["box_spacing"])
    ijk = np.stack(np.meshgrid(*[np.arange(n) for n in shape], indexing="ij"), axis=-1).reshape(-1, 3)
    points = data["box_origin"] + ijk * spacing
    dg, ig = cKDTree(guest_pos).query(points, workers=-1)
    dh, ih = cKDTree(host_pos).query(points, workers=-1)
    pair = np.linalg.norm(guest_pos[ig] - host_pos[ih], axis=1)
    mask = (dg + dh < pair + tolerance) & (dg <= guest_reach) & (dh <= reach) & (dg >= inside) & (dh >= inside)
    return mask.reshape(shape), points.reshape(*shape, 3)


def mark_contact(viewer, data, keep):
    """Label the screened O-H...O contact on a viewer that shows only the atoms listed in `keep`."""
    for _, hydrogen, acceptor in data["hbond"]:
        position = {int(a): k for k, a in enumerate(keep)}
        distance = np.linalg.norm(data["positions"][hydrogen] - data["positions"][acceptor])
        viewer.add_distance(position[int(hydrogen)], position[int(acceptor)], label=f"H···O {distance:.3f} Å")


NEAR = 4.5  # angstrom: host atoms shown around the guest in the field viewers


def field_figures(data, atoms, out, density_isovalue, stride=2):
    full = atoms
    positions = full.get_positions()
    near_host = np.flatnonzero(cKDTree(positions[HOST_ATOMS:]).query(positions[:HOST_ATOMS])[0] <= NEAR)
    keep = np.concatenate([near_host, np.arange(HOST_ATOMS, len(full))])
    atoms = full[list(keep)]
    colors = [HOST if k < HOST_ATOMS else GUEST_COLOR for k in keep]
    look = {"atom_colors": colors, "color_legend": {HOST: f"host atoms within {NEAR} Å of the guest", GUEST_COLOR: "guest (thymol)"}, **STYLE}
    spacing = float(data["box_spacing"])
    # density difference, cropped to the guest box
    origin, axes = data["origin"], data["axes"]
    lo, hi = data["box_origin"], data["box_origin"] + spacing * np.array(data["rdg"].shape)
    i0 = np.maximum(np.floor((lo - origin) / np.diag(axes)).astype(int), 0)
    i1 = np.minimum(np.ceil((hi - origin) / np.diag(axes)).astype(int), np.array(data["delta"].shape))
    sl = tuple(slice(a, b, stride) for a, b in zip(i0, i1))
    delta = data["delta"][sl]
    d_origin = origin + i0 * np.diag(axes)
    viewer = FieldViewer(atoms, field_dict("density_difference", delta, d_origin, axes * stride, "electron/angstrom^3"),
                         isovalue=density_isovalue, surface="both", opacity=0.8, positive_color="#2563eb",
                         negative_color="#ea580c", title="Density difference", height=520, look=look)
    frame_camera(viewer, full, list(range(HOST_ATOMS, len(full))), distance=30, side=True, zoom=1.5)
    mark_contact(viewer, data, keep)
    viewer.write_spec(out / "cyclodextrin-delta-rho.json", snapshot_path=out / "cyclodextrin-delta-rho.snapshot.json",
                      snapshot_url="/figures/cyclodextrin/cyclodextrin-delta-rho.snapshot.json",
                      isovalue_range=(density_isovalue / 4, density_isovalue * 4))
    # NCI isosurface restricted to the host-guest interface
    interface, _ = interface_mask(data)
    interface &= np.abs(data["slr"]) < 0.35
    rdg = np.where(interface, data["rdg"], 5.0)
    rdg, slr = rdg[::stride, ::stride, ::stride], np.clip(data["slr"][::stride, ::stride, ::stride], -0.15, 0.15)
    n_axes = np.eye(3) * spacing * stride
    viewer = FieldViewer(atoms, field_dict("reduced_density_gradient", rdg, data["box_origin"], n_axes, "1"),
                         isovalue=0.6, color_by=field_dict("sign_lambda2_rho", slr, data["box_origin"], n_axes, "electron/angstrom^3"),
                         colormap="diverging", surface="positive", opacity=0.9, title="NCI", height=520, look=look)
    frame_camera(viewer, full, list(range(HOST_ATOMS, len(full))), distance=30, side=True, zoom=1.5)
    mark_contact(viewer, data, keep)
    viewer.write_spec(out / "cyclodextrin-nci.json", snapshot_path=out / "cyclodextrin-nci.snapshot.json",
                      snapshot_url="/figures/cyclodextrin/cyclodextrin-nci.snapshot.json", isovalue_range=(0.3, 1.0))


def nci_scatter(data, out, summary, rng=np.random.default_rng(7)):
    spacing = float(data["box_spacing"])
    interface, pts = interface_mask(data)
    interface &= (data["rdg"] < 2.0) & (np.abs(data["slr"]) < 0.35)
    low = interface & (data["rdg"] < 0.5)
    values = data["slr"][low]
    summary["interface_points_rdg_below_0.5"] = int(low.sum())
    summary["interface_attractive_below_-0.02"] = int((values < -0.02).sum())
    summary["interface_vdw_within_0.02"] = int((np.abs(values) <= 0.02).sum())
    summary["interface_repulsive_above_0.02"] = int((values > 0.02).sum())
    summary["interface_min_slr"] = float(values.min())
    traces = []
    mask = interface.copy()
    spike = np.zeros_like(interface)
    if len(data["hbond"]):
        _, h, acceptor = data["hbond"][0]
        a, b = data["positions"][h], data["positions"][acceptor]
        t = np.clip(((pts - a) @ (b - a)) / np.dot(b - a, b - a), 0, 1)
        dist = np.linalg.norm(pts - (a + t[..., None] * (b - a)), axis=-1)
        spike = interface & (dist < 0.45) & (data["rdg"] < 0.5)
        summary["spike_rdg_min"] = float(data["rdg"][spike].min()) if spike.any() else None
        mask &= ~spike
    idx = np.flatnonzero(mask)
    keep = rng.choice(idx, size=min(len(idx), 8000), replace=False)
    traces.append({"type": "scatter", "mode": "markers", "name": "host-guest interface", "x": data["slr"].ravel()[keep].tolist(),
                   "y": data["rdg"].ravel()[keep].tolist(), "marker": {"size": 3, "color": "#8896a8", "opacity": 0.5},
                   "hoverinfo": "skip"})
    if spike.any():
        s = np.flatnonzero(spike)
        traces.append({"type": "scatter", "mode": "markers", "name": "along the H···O contact", "x": data["slr"].ravel()[s].tolist(),
                       "y": data["rdg"].ravel()[s].tolist(), "marker": {"size": 5, "color": "#dc4b4b"}, "hoverinfo": "skip"})
        summary["spike_points"] = int(len(s))
        summary["spike_min_slr"] = float(data["slr"].ravel()[s].min())
    figure = {"data": traces, "layout": {
        "xaxis": {"title": {"text": "sign(λ₂)ρ (e/Å³)"}, "range": [-0.3, 0.3]},
        "yaxis": {"title": {"text": "Reduced density gradient s"}, "range": [0, 2]},
        "legend": {"orientation": "h", "x": 0.5, "xanchor": "center", "y": -0.28}, "margin": {"l": 70, "r": 20, "t": 20, "b": 100}}}
    plot.plotly(figure).write_spec(out / "cyclodextrin-nci-scatter.json")


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--results", type=Path, required=True)
    parser.add_argument("--models", type=Path, required=True)
    parser.add_argument("--work", type=Path, required=True)
    parser.add_argument("--figures", type=Path, required=True)
    parser.add_argument("--delta-isovalue", type=float, default=0.004)
    args = parser.parse_args()
    out = args.figures
    out.mkdir(parents=True, exist_ok=True)
    pose_plot(args.results, out)
    start_viewer(args.models, out)
    contact_viewers(args.results, out, [("thymol", 2, "thymol"), ("carvacrol", 1, "carvacrol")])
    summary = json.loads((args.work / "analysis.json").read_text())
    data = dict(np.load(args.work / "fields.npz"))
    atoms = read(args.results / f"{summary['guest']}-{summary['pose']}.xyz")
    atoms.set_pbc(False)
    fukui_figures(summary, atoms, out)
    field_figures(data, atoms, out, args.delta_isovalue)
    figure_summary = {}
    nci_scatter(data, out, figure_summary)
    (args.work / "figure-summary.json").write_text(json.dumps(figure_summary, indent=2) + "\n")


if __name__ == "__main__":
    main()
