"""Water: three vibrational modes against gas-phase fundamentals.

Reads the molecule written by water-modes-build.py, relaxes it with PBE/def2-SVP,
takes the analytical Hessian, and writes a study (numbers, linked plot and
structure, table, provenance) that the docs page mounts natively.

    python water-modes-run.py --models ../models --output ../../studies/water-modes
"""
import argparse
from pathlib import Path

import numpy as np

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

# Gas-phase H2O fundamentals, cm^-1: Shimanouchi, Tables of Molecular
# Vibrational Frequencies, Consolidated Volume I, NSRDS-NBS 39 (1972).
OBSERVED = {"bend": 1595.0, "symmetric-stretch": 3657.0, "antisymmetric-stretch": 3756.0}
NAMES = {"bend": "bend", "symmetric-stretch": "symmetric stretch", "antisymmetric-stretch": "antisymmetric stretch"}
AMPLITUDE = 0.15  # largest atom displacement shown, angstrom
FRAMES = 24


def geometry(atoms):
    positions = atoms.get_positions()
    first, second = positions[1] - positions[0], positions[2] - positions[0]
    angle = np.degrees(np.arccos(first @ second / np.linalg.norm(first) / np.linalg.norm(second)))
    return float(np.linalg.norm(first)), float(angle)


def classify(atoms, displacements):
    """Name the three vibrational modes from how they change the two O-H bonds."""
    positions = atoms.get_positions()
    unit = [(positions[h] - positions[0]) / np.linalg.norm(positions[h] - positions[0]) for h in (1, 2)]
    named = {}
    ordered = sorted(range(3), key=lambda k: displacements[k][0])  # ascending frequency
    named["bend"] = ordered[0]
    stretch = []
    for k in ordered[1:]:
        mode = displacements[k][1]
        stretch.append((k, float((mode[1] - mode[0]) @ unit[0]) * float((mode[2] - mode[0]) @ unit[1])))
    # Symmetric stretch lengthens both bonds together, so the product is positive.
    symmetric = max(stretch, key=lambda item: item[1])[0]
    named["symmetric-stretch"] = symmetric
    named["antisymmetric-stretch"] = next(k for k, _ in stretch if k != symmetric)
    return named


def mode_frames(atoms, mode):
    mode = np.asarray(mode, dtype=float)
    mode = mode * AMPLITUDE / np.linalg.norm(mode, axis=1).max()
    frames = []
    for step in range(FRAMES):
        image = atoms.copy()
        image.set_positions(atoms.get_positions() + np.sin(2 * np.pi * step / FRAMES) * mode)
        frames.append(image)
    return frames


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--models", type=Path, default=Path(__file__).resolve().parents[1] / "models")
    parser.add_argument("--output", required=True)
    args = parser.parse_args()
    output = Path(args.output)

    atoms = read(args.models / "h2o-start.extxyz")
    atoms.calc = QC(xc="PBE", basis="def2-SVP")
    BFGS(atoms).run(fmax=0.003, steps=100)
    r_oh, angle = geometry(atoms)

    vib = Vibrations(atoms).run()
    frequencies = np.asarray(vib.get_frequencies()).real
    top = np.argsort(frequencies)[-3:]  # the six rigid-body modes lie below
    modes = [(frequencies[index], vib.get_mode(index)) for index in top]
    named = classify(atoms, modes)

    computed = {name: float(modes[k][0]) for name, k in named.items()}
    error = {name: computed[name] - OBSERVED[name] for name in OBSERVED}
    order = ["bend", "symmetric-stretch", "antisymmetric-stretch"]

    # Computed sticks and observed diamonds on a broken axis, so the 10 to 40 cm^-1 gaps show.
    def axis(name):
        return "x" if name == "bend" else "x2"

    data = [
        {"type": "scatter", "mode": "lines", "xaxis": axis(n), "x": [computed[n], OBSERVED[n]], "y": [1, 1],
         "line": {"color": "#8a8f98", "width": 1.5}, "hoverinfo": "skip", "showlegend": False}
        for n in order
    ]
    for which, names in (("x", ["bend"]), ("x2", order[1:])):
        data.append({"type": "bar", "xaxis": which, "x": [computed[n] for n in names], "y": [1] * len(names),
                     "width": 3 if which == "x" else 4, "marker": {"color": "#2266cc"}, "name": "PBE/def2-SVP",
                     "showlegend": which == "x", "customdata": names, "textposition": "none",
                     "text": [f"{NAMES[n]}: {computed[n]:.1f} cm⁻¹" for n in names], "hovertemplate": "%{text}<extra></extra>"})
        data.append({"type": "scatter", "mode": "markers", "xaxis": which, "x": [OBSERVED[n] for n in names], "y": [1] * len(names),
                     "marker": {"symbol": "diamond", "size": 12, "color": "#dc4b4b"}, "name": "Observed",
                     "showlegend": which == "x", "customdata": names,
                     "text": [f"{NAMES[n]}: {OBSERVED[n]:.1f} cm⁻¹ observed" for n in names], "hovertemplate": "%{text}<extra></extra>"})
    layout = {
        "margin": {"l": 20, "r": 16, "t": 36, "b": 52},
        "legend": {"orientation": "h", "y": 1.14, "x": 0},
        "annotations": [
            {"xref": axis(n), "yref": "y", "x": (computed[n] + OBSERVED[n]) / 2, "y": 1.1, "showarrow": False,
             "text": f"{error[n]:+.1f}".replace("-", "−")}
            for n in order
        ],
        "xaxis": {"domain": [0, 0.26], "range": [1560, 1660], "tickvals": [1580, 1620, 1660],
                  "title": {"text": "Wavenumber (cm⁻¹)", "standoff": 8}},
        "xaxis2": {"domain": [0.34, 1], "range": [3600, 3820], "tickvals": [3650, 3700, 3750, 3800], "anchor": "y"},
        "yaxis": {"visible": False, "range": [0, 1.22]},
        "bargap": 0,
    }
    spectrum = plot.plotly({"data": data, "layout": layout}, title="Computed and observed fundamentals of water")

    states = {}
    for name in order:
        viewer = Viewer(mode_frames(atoms, modes[named[name]][1]), height=440)
        viewer.set_fps(12).play()
        states[name] = viewer

    study = Study("water-modes", "Water: three modes and how far PBE misses them",
                  system="H2O, gas phase, neutral singlet", method="PBE/def2-SVP, analytical Hessian")
    study.fact("r_oh", r_oh, "Å", label="O–H bond", precision=3)
    study.fact("angle", angle, "°", label="H–O–H angle", precision=2)
    study.fact("zpe", float(vib.get_zero_point_energy()), "eV", label="Zero-point energy", precision=3)
    study.fact("max_error", max(error.values(), key=abs), "cm⁻¹", label="Largest error", precision=1)
    study.figure("modes", spectrum, height=440, caption="Computed (bars) against observed (diamonds). The number above each pair is computed minus observed, in cm⁻¹.")
    study.figure("structure", states["bend"], height=440, caption="Normal mode, amplitude exaggerated:")
    study.link("mode", source="modes", target="structure", states=states, initial="bend", labels=NAMES)
    study.table(
        "errors",
        [{"key": "mode", "label": "Mode", "align": "left"},
         {"key": "computed", "label": "PBE/def2-SVP", "unit": "cm⁻¹", "precision": 1},
         {"key": "observed", "label": "Observed", "unit": "cm⁻¹", "precision": 1},
         {"key": "error", "label": "Error", "unit": "cm⁻¹", "precision": 1},
         {"key": "percent", "label": "Error", "unit": "%", "precision": 1}],
        [{"id": n, "mode": NAMES[n], "computed": round(computed[n], 1), "observed": OBSERVED[n],
          "error": round(error[n], 1), "percent": round(100 * error[n] / OBSERVED[n], 1)} for n in order],
        select="mode",
    )
    study.provenance("Computed", "atomli QC, PBE/def2-SVP, geometry relaxed to fmax 0.003 eV/Å, analytical Hessian")
    study.provenance("Observed", "gas-phase H2O fundamentals from Shimanouchi, NSRDS-NBS 39 (1972)")
    print(study.write(output))


if __name__ == "__main__":
    main()
