"""SN2 Cl- + CH3Cl, calculation stage: climbing-image NEB and TS search.

Reads inputs written by sn2-neb-build.py. PBE/def2-TZVP (no diffuse basis is
available in atomli QC), charge -1, singlet, analytical forces and Hessians.
Also computes the separated reactants Cl- + CH3Cl at the same level. Steps:
relax both complexes, relax a 15-image IDPP band
(ordinary NEB, then climbing image), refine the highest image with eigenvector
following on analytical Hessians, check the Hessian for one imaginary mode, and
relax from both sides of that mode to confirm what the saddle connects.
Writes study.json for the docs page. Needs ASE for the band driver.

    python sn2-neb-run.py --output ../../studies/sn2-neb-ts
"""
import argparse
import json
import time
from pathlib import Path

import numpy as np
from ase import Atoms as AseAtoms
from ase.mep import NEB
from ase.optimize import BFGS as BandBFGS

from atomli import Atoms
from atomli.analysis import analyze_reaction_path, interpolate_reaction_path
from atomli.calculators.qc import QC
from atomli.io import read
from atomli.optimize import BFGS
from atomli.vibrations import Vibrations
from atomli.visualize import Study, Viewer, plot

EV_TO_KCAL = 23.060548  # kcal/mol per eV (thermochemical calorie)
K_SPRING = 0.1          # eV/A^2
FMAX_BAND = 0.03        # ordinary NEB stage, eV/A
FMAX_CLIMB = 0.01       # climbing-image stage, eV/A
MODE_SCALE = 0.15       # largest atom displacement of the animated mode, angstrom
PUSH = 0.10             # largest atom displacement used to leave the saddle, angstrom


BASIS = "def2-TZVP"


def calculator(charge=-1):
    return QC(xc="PBE", basis=BASIS, charge=charge, device="cpu", scf={"energy_tolerance": 1e-8}, maxiter=200)


def native(atoms):
    return Atoms(atoms.get_chemical_symbols(), positions=atoms.get_positions())


def with_calc(atoms):
    atoms = native(atoms)
    atoms.calc = calculator()
    return atoms


def fmax(atoms):
    return float(np.linalg.norm(atoms.get_forces(), axis=1).max())


def kabsch_rmsd(a, b):
    """RMSD after the best proper rotation and translation, atom labels fixed."""
    a = a.get_positions() - a.get_positions().mean(axis=0)
    b = b.get_positions() - b.get_positions().mean(axis=0)
    u, s, vt = np.linalg.svd(a.T @ b)
    d = np.sign(np.linalg.det(u @ vt))
    r = u @ np.diag([1, 1, d]) @ vt
    return float(np.sqrt(np.mean(np.sum((a @ r - b) ** 2, axis=1))))


def dist(atoms, i, j):
    p = atoms.get_positions()
    return float(np.linalg.norm(p[i] - p[j]))


def cl_c_cl(atoms):
    p = atoms.get_positions()
    u, v = p[4] - p[0], p[5] - p[0]
    return float(np.degrees(np.arccos(u @ v / np.linalg.norm(u) / np.linalg.norm(v))))


def c_height(atoms):
    """Height of C above the plane through the three H atoms, angstrom (signed along Cl a -> Cl b)."""
    p = atoms.get_positions()
    normal = np.cross(p[2] - p[1], p[3] - p[1])
    normal /= np.linalg.norm(normal)
    if normal @ (p[5] - p[4]) < 0:
        normal = -normal
    return float((p[0] - p[1:4].mean(axis=0)) @ normal)


def rigid_projector(atoms):
    """Projector onto internal coordinates: removes translations and rotations."""
    p = atoms.get_positions() - atoms.get_positions().mean(axis=0)
    vectors = []
    for axis in np.eye(3):
        vectors.append(np.tile(axis, (len(p), 1)).ravel())
        vectors.append(np.cross(axis, p).ravel())
    q, _ = np.linalg.qr(np.array(vectors).T)
    return np.eye(3 * len(p)) - q @ q.T


def refine_ts(atoms, log):
    """Eigenvector following with analytical Hessians: climb the lowest internal mode, descend the rest."""
    for iteration in range(1, 13):
        atoms.calc = calculator()
        hessian = np.asarray(Vibrations(atoms, method="analytical").run().get_hessian_2d(), dtype=float)
        force = np.asarray(atoms.get_forces(), dtype=float).ravel()
        proj = rigid_projector(atoms)
        values, vectors = np.linalg.eigh(proj @ (hessian + hessian.T) / 2 @ proj)
        internal = np.abs(values) > 1e-3  # rigid-body eigenvalues are ~0 after projection
        values, vectors = values[internal], vectors[:, internal]
        g = vectors.T @ (-force)                      # gradient in the eigenbasis
        step = np.zeros_like(g)
        # Maximize along the lowest mode, minimize along the others (P-RFO, shift per subspace).
        shift_max = 0.5 * (values[0] + np.sqrt(values[0] ** 2 + 4 * g[0] ** 2))
        step[0] = -g[0] / (values[0] - shift_max)
        rest = values[1:]
        shift_min = 0.5 * (rest[0] - np.sqrt(rest[0] ** 2 + 4 * np.sum(g[1:] ** 2)))
        step[1:] = -g[1:] / (rest - shift_min)
        dx = (vectors @ step).reshape(-1, 3)
        longest = np.linalg.norm(dx, axis=1).max()
        if longest > 0.1:
            dx *= 0.1 / longest
        residual = fmax(atoms)
        log.append({"iteration": iteration, "fmax_ev_per_angstrom": residual,
                    "lowest_hessian_eigenvalue_ev_per_angstrom2": float(values[0]),
                    "step_angstrom": float(longest)})
        print(f"TS iteration {iteration}: fmax {residual:.4f}, step {longest:.4f}", flush=True)
        if residual < 0.002 and longest < 0.005:
            return atoms
        atoms.set_positions(atoms.get_positions() + dx)
    raise RuntimeError("TS refinement did not converge")


def descend(start, direction, scale):
    """Relax from the saddle displaced along `direction`; return (frames, relaxed atoms)."""
    atoms = native(start)
    atoms.set_positions(start.get_positions() + direction * scale / np.linalg.norm(direction, axis=1).max())
    atoms.calc = calculator()
    frames = [native(atoms)]
    optimizer = BFGS(atoms, maxstep=0.1, logfile=None)
    optimizer.attach(lambda: frames.append(native(atoms)), interval=1)
    if not optimizer.run(fmax=0.003, steps=500):
        raise RuntimeError("Downhill relaxation did not converge")
    return frames, atoms


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--output", required=True)
    output = Path(parser.parse_args().output)
    logs = output / "logs"
    logs.mkdir(parents=True, exist_ok=True)
    timings = {}
    clock = time.time()

    def lap(name):
        nonlocal clock
        timings[name] = round(time.time() - clock, 1)
        clock = time.time()
        print(f"{name}: {timings[name]} s", flush=True)

    # 1. Endpoints: relax both minima.
    minima = {}
    endpoint_fmax = {}
    for name in ("reactant", "product"):
        atoms = read(output / "inputs" / f"{name}.xyz")
        atoms.calc = calculator()
        if not BFGS(atoms, maxstep=0.12, logfile=None).run(fmax=0.001, steps=400):
            raise RuntimeError(f"{name} did not converge")
        endpoint_fmax[name] = fmax(atoms)
        minima[name] = native(atoms)
    energies_min = {}
    for name, atoms in minima.items():
        atoms.calc = calculator()
        energies_min[name] = float(atoms.get_potential_energy())
    lap("endpoints")

    # Separated reactants at the same level: Cl- and relaxed CH3Cl.
    chloride = Atoms("Cl", positions=[[0.0, 0.0, 0.0]])
    chloride.calc = calculator(-1)
    e_chloride = float(chloride.get_potential_energy())
    keep = [0, 1, 2, 3, 5]
    ch3cl = Atoms([minima["reactant"].get_chemical_symbols()[k] for k in keep],
                  positions=minima["reactant"].get_positions()[keep])
    ch3cl.calc = calculator(0)
    if not BFGS(ch3cl, maxstep=0.1, logfile=None).run(fmax=0.001, steps=200):
        raise RuntimeError("CH3Cl did not converge")
    e_ch3cl = float(ch3cl.get_potential_energy())
    e_separated = e_chloride + e_ch3cl
    lap("separated reactants")

    # 2. Band: IDPP from the relaxed minima, single points on the initial band.
    n_images = len(read(output / "inputs" / "initial-band.extxyz", index=":"))
    initial_band = interpolate_reaction_path(minima["reactant"], minima["product"], n_images=n_images, method="idpp", mic=False)
    initial_energies = []
    for image in initial_band:
        image = with_calc(image)
        initial_energies.append(float(image.get_potential_energy()))
    lap("initial band energies")

    images = []
    for image in initial_band:
        a = AseAtoms(image.get_chemical_symbols(), positions=image.get_positions())
        a.calc = calculator()
        images.append(a)
    band = NEB(images, k=K_SPRING, climb=False, method="improvedtangent")
    ordinary = BandBFGS(band, maxstep=0.08, logfile=str(logs / "neb.log"))
    if not ordinary.run(fmax=FMAX_BAND, steps=300):
        raise RuntimeError("Ordinary NEB did not converge")
    steps_ordinary = int(ordinary.nsteps)
    band.climb = True
    climbing = BandBFGS(band, maxstep=0.04, logfile=str(logs / "ci-neb.log"))
    if not climbing.run(fmax=FMAX_CLIMB, steps=300):
        raise RuntimeError("Climbing-image NEB did not converge")
    steps_climb = int(climbing.nsteps)
    band_fmax = float(np.linalg.norm(band.get_forces(), axis=1).max())
    energies = np.array([float(a.get_potential_energy()) for a in images])
    forces = np.array([a.get_forces() for a in images])
    path = [native(a) for a in images]
    result = analyze_reaction_path(path, energies_ev=energies, forces=forces)
    lap("neb")

    # 3. Refine the highest image with Hessian eigenvector following.
    candidate = with_calc(path[result.ts_index])
    refinement = []
    ts = refine_ts(candidate, refinement)
    ts.calc = calculator()
    ts_energy = float(ts.get_potential_energy())
    ts_fmax = fmax(ts)
    lap("ts refinement")

    # 4. Hessian at the refined TS.
    vib = Vibrations(ts, method="analytical").run()
    frequencies = np.asarray(vib.get_frequencies())
    signed = frequencies.real - frequencies.imag
    unstable = [int(i) for i in np.flatnonzero(signed < -100)]
    if len(unstable) != 1:
        raise RuntimeError(f"Expected one imaginary mode, found {len(unstable)}")
    mode_index = unstable[0]
    imaginary = float(-signed[mode_index])  # magnitude, cm^-1
    mode = np.asarray(vib.get_mode(mode_index), dtype=float)
    lap("ts hessian")

    # 5. Connectivity: leave the saddle both ways along the mode and relax.
    frames_plus, end_plus = descend(ts, mode, PUSH)
    frames_minus, end_minus = descend(ts, -mode, PUSH)
    for end in (end_plus, end_minus):
        end.calc = calculator()
    ends = {"plus": end_plus, "minus": end_minus}
    energy_ends = {k: float(v.get_potential_energy()) for k, v in ends.items()}
    rmsd = {k: {"reactant": kabsch_rmsd(v, minima["reactant"]), "product": kabsch_rmsd(v, minima["product"])}
            for k, v in ends.items()}
    lap("connectivity")

    # 6. Assemble study.
    ref = energies_min["reactant"]
    rel = (energies - ref)
    ids = [f"i{index:02d}" for index in range(len(images))]
    arc = result.reaction_coordinate_angstrom
    forward = ts_energy - energies_min["reactant"]
    reverse = ts_energy - energies_min["product"]
    forward_band = float(result.forward_barrier_ev)

    mode_frames = []
    scaled = mode * MODE_SCALE / np.linalg.norm(mode, axis=1).max()
    for phase in np.linspace(0, 2 * np.pi, 24, endpoint=False):
        frame = native(ts)
        frame.set_positions(ts.get_positions() + np.sin(phase) * scaled)
        mode_frames.append(frame)

    def scatter_initial():
        initial_arc = [0.0]
        for a, b in zip(initial_band[:-1], initial_band[1:]):
            initial_arc.append(initial_arc[-1] + float(np.linalg.norm(b.get_positions() - a.get_positions())))
        return initial_arc

    initial_arc = scatter_initial()
    data = [
        {"type": "scatter", "mode": "lines+markers", "x": initial_arc,
         "y": [float(e - ref) for e in initial_energies], "name": "Initial IDPP band",
         "line": {"color": "#8a8f98", "width": 1.5, "dash": "dot"}, "marker": {"size": 6, "color": "#8a8f98"},
         "hoverinfo": "skip"},
        {"type": "scatter", "mode": "lines+markers", "x": [float(v) for v in arc], "y": [float(v) for v in rel],
         "name": "Relaxed band, one marker per image", "customdata": ids,
         "line": {"color": "#2266cc", "width": 2},
         "marker": {"size": [14 if i == result.ts_index else 9 for i in range(len(images))],
                    "symbol": ["diamond" if i == result.ts_index else "circle" for i in range(len(images))],
                    "color": ["#dc4b4b" if i == result.ts_index else "#2266cc" for i in range(len(images))]},
         "text": [f"image {i}" for i in range(len(images))],
         "hovertemplate": "%{text}<br>%{y:.3f} eV<extra></extra>"},
        {"type": "scatter", "mode": "lines", "x": [0.0, float(arc[-1])], "y": [float(e_separated - ref)] * 2,
         "name": "Separated Cl⁻ + CH₃Cl", "line": {"color": "#dc4b4b", "width": 1.5, "dash": "dash"},
         "hoverinfo": "skip"},
    ]
    layout = {
        "margin": {"l": 64, "r": 16, "t": 16, "b": 96},
        "legend": {"orientation": "h", "y": -0.28, "x": 0},
        "xaxis": {"title": {"text": "Cumulative path length (Å)", "standoff": 8}},
        "yaxis": {"title": {"text": "Energy relative to reactant complex (eV)", "standoff": 8}},
    }
    profile = plot.plotly({"data": data, "layout": layout}, title="Energy along the SN2 band, Cl⁻ + CH₃Cl")

    def view(frames, fps=None):
        v = Viewer(frames, height=440, look={"labels": False})
        if fps:
            v.set_fps(fps).play()
        return v

    states = {"band": view(path, 6)}
    for i, image in enumerate(path):
        states[ids[i]] = view([image])
    states["ts"] = view([ts])
    states["ts-mode"] = view(mode_frames, 12)
    states["descent-plus"] = view(frames_plus, 8)
    states["descent-minus"] = view(frames_minus, 8)
    labels = {"band": "Relaxed band, all images", "ts": "Refined transition state",
              "ts-mode": "Imaginary mode at the transition state",
              "descent-plus": "Relaxation after displacing along +mode",
              "descent-minus": "Relaxation after displacing along −mode"}
    for i in range(len(images)):
        labels[ids[i]] = f"Image {i}"

    nearest = {k: min(rmsd[k], key=rmsd[k].get) for k in rmsd}
    if set(nearest.values()) != {"reactant", "product"}:
        raise RuntimeError(f"The two descents do not reach both minima: {rmsd}")

    study = Study("sn2-neb-ts", "SN2 Cl⁻ + CH₃Cl: band, saddle and connectivity",
                  system="Cl⁻ + CH₃Cl, gas phase, charge -1, singlet",
                  method=f"PBE/{BASIS}, climbing-image NEB, analytical forces and Hessian")
    study.fact("barrier_ev", forward, "eV", label="Barrier above the complex", precision=3)
    study.fact("barrier_kcal", forward * EV_TO_KCAL, "kcal/mol", label="Barrier above the complex", precision=2)
    study.fact("well_ev", e_separated - ref, "eV", label="Complex below separated reactants", precision=3)
    study.fact("well_kcal", (e_separated - ref) * EV_TO_KCAL, "kcal/mol", label="Complex below separated reactants", precision=2)
    study.fact("ts_vs_separated_ev", ts_energy - e_separated, "eV", label="TS relative to separated reactants", precision=3)
    study.fact("imaginary", imaginary, "cm⁻¹", label="Imaginary frequency", precision=0)
    study.fact("rcl_ts", dist(ts, 0, 4), "Å", label="C–Cl(a) at TS", precision=3)
    study.fact("rcl_ts_b", dist(ts, 0, 5), "Å", label="C–Cl(b) at TS", precision=3)
    study.fact("clccl_ts", cl_c_cl(ts), "°", label="Cl–C–Cl at TS", precision=1)
    study.fact("height_ts", abs(c_height(ts)), "Å", label="C above H₃ plane at TS", precision=3)
    study.fact("height_min", abs(c_height(minima["reactant"])), "Å", label="C above H₃ plane in the complex", precision=3)
    study.fact("rbond_min", dist(minima["reactant"], 0, 5), "Å", label="C–Cl(b) in the complex", precision=3)
    study.fact("rfree_min", dist(minima["reactant"], 0, 4), "Å", label="C···Cl(a) in the complex", precision=3)
    study.figure("profile", profile, height=440,
                 caption="Relaxed band images (blue; the highest, which holds the saddle, is the red diamond) the initial IDPP band (grey) and the separated Cl⁻ + CH₃Cl reference (red dashed). Click an image to load it.")
    study.figure("structure", states["band"], height=440, caption="Structure:")
    study.link("path", source="profile", target="structure", states=states, initial="band", labels=labels)

    rows = [{"id": "band", "label": labels["band"], "energy_ev": "–", "energy_kcal": "–", "da": "–", "db": "–", "check": f"{len(images)} images"}]
    for i, image in enumerate(path):
        rows.append({"id": ids[i], "label": labels[ids[i]], "energy_ev": round(float(rel[i]), 4) + 0.0,
                     "energy_kcal": round(float(rel[i] * EV_TO_KCAL), 2) + 0.0,
                     "da": round(dist(image, 0, 4), 3), "db": round(dist(image, 0, 5), 3), "check": "climbing" if i == result.ts_index else ""})
    rows.append({"id": "ts", "label": labels["ts"], "energy_ev": round(ts_energy - ref, 4),
                 "energy_kcal": round((ts_energy - ref) * EV_TO_KCAL, 2), "da": round(dist(ts, 0, 4), 3), "db": round(dist(ts, 0, 5), 3),
                 "check": f"1 imaginary mode, {imaginary:.0f}i cm⁻¹"})
    rows.append({"id": "ts-mode", "label": labels["ts-mode"], "energy_ev": "–", "energy_kcal": "–", "da": "–", "db": "–",
                 "check": f"{imaginary:.0f}i cm⁻¹, 0.15 Å amplitude"})
    for key, state in (("plus", "descent-plus"), ("minus", "descent-minus")):
        end = ends[key]
        rows.append({"id": state, "label": labels[state], "energy_ev": round(energy_ends[key] - ref, 4) + 0.0,
                     "energy_kcal": round((energy_ends[key] - ref) * EV_TO_KCAL, 2) + 0.0, "da": round(dist(end, 0, 4), 3), "db": round(dist(end, 0, 5), 3),
                     "check": f"ends at {nearest[key]}, RMSD {rmsd[key][nearest[key]]:.4f} Å"})
    study.table("states", [
        {"key": "label", "label": "State", "align": "left"},
        {"key": "energy_ev", "label": "Energy", "unit": "eV", "precision": 3},
        {"key": "energy_kcal", "label": "Energy", "unit": "kcal/mol", "precision": 1},
        {"key": "da", "label": "C–Cl(a)", "unit": "Å", "precision": 3},
        {"key": "db", "label": "C–Cl(b)", "unit": "Å", "precision": 3},
        {"key": "check", "label": "Note", "align": "left"},
    ], rows, select="path")
    study.provenance("Energies, forces, Hessians", f"atomli QC, PBE/{BASIS} (no diffuse functions), charge -1, SCF energy tolerance 1e-8 Eh, analytical nuclear derivatives")
    study.provenance("Band", f"{n_images} images, IDPP initial guess between relaxed minima, ASE improved-tangent NEB, spring {K_SPRING} eV/Å², "
                             f"BFGS: {steps_ordinary} steps to fmax {FMAX_BAND} eV/Å, then {steps_climb} climbing-image steps to {FMAX_CLIMB} eV/Å")
    study.provenance("Transition state", f"Highest NEB image, then P-RFO eigenvector following on analytical Hessians ({len(refinement)} Hessian evaluation before the step fell below 0.005 Å); residual force {ts_fmax:.4f} eV/Å")
    study.provenance("Conversion", f"1 eV = {EV_TO_KCAL} kcal/mol; energies are electronic, without zero-point correction or counterpoise correction")
    study.write(output)

    extra = {
        "energies_ev": energies.tolist(), "initial_band_energies_ev": initial_energies,
        "minima_energies_ev": energies_min, "chloride_energy_ev": e_chloride, "ch3cl_energy_ev": e_ch3cl, "separated_energy_ev": e_separated, "endpoint_fmax_ev_per_angstrom": endpoint_fmax,
        "ts_energy_ev": ts_energy, "ts_fmax_ev_per_angstrom": ts_fmax,
        "forward_barrier_ev": forward, "reverse_barrier_ev": reverse,
        "forward_barrier_from_band_ev": forward_band,
        "highest_image": int(result.ts_index),
        "neb_steps_ordinary": steps_ordinary, "neb_steps_climbing": steps_climb,
        "neb_fmax_final_ev_per_angstrom": band_fmax,
        "refinement": refinement, "frequencies_cm_inv": signed.tolist(), "imaginary_cm_inv": imaginary,
        "connectivity": {"energy_ev": energy_ends, "rmsd_angstrom": rmsd, "nearest": nearest},
        "reflection_energy_difference_ev": energies_min["product"] - energies_min["reactant"],
        "timings_s": timings,
    }
    (output / "results.json").write_text(json.dumps(extra, indent=1))
    print(json.dumps({k: v for k, v in extra.items() if k not in ("refinement",)}, indent=1))


if __name__ == "__main__":
    main()
