"""Ammonia umbrella inversion, build stage: endpoints and the initial band.

Constructs the two pyramidal minima of NH3 (mirror images through the H3 plane)
and an IDPP interpolation between them. No calculator is attached and no
energy is computed. Writes inputs for ammonia-neb-run.py.

    python ammonia-neb-build.py --output ../../studies/ammonia-neb-ts
"""
import argparse
from pathlib import Path

import numpy as np

from atomli import Atoms
from atomli.analysis import interpolate_reaction_path
from atomli.io import write
from atomli.visualize import Viewer

R_NH = 1.012       # angstrom, starting N-H distance
ANGLE_HNH = 106.7  # degrees, starting H-N-H angle
N_IMAGES = 11      # frames in the band, endpoints included


def pyramid(sign):
    """NH3 with C3 axis along z, H atoms in the z = 0 plane, N at z = sign * h."""
    rho = 2 * R_NH * np.sin(np.radians(ANGLE_HNH) / 2) / np.sqrt(3)
    height = np.sqrt(R_NH**2 - rho**2)
    hydrogens = [[rho * np.cos(a), rho * np.sin(a), 0.0] for a in np.radians([0, 120, 240])]
    return Atoms("NH3", positions=[[0, 0, sign * height]] + hydrogens)


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--output", required=True)
    output = Path(parser.parse_args().output)
    inputs = output / "inputs"
    inputs.mkdir(parents=True, exist_ok=True)

    reactant, product = pyramid(+1), pyramid(-1)
    write(inputs / "reactant.xyz", reactant)
    write(inputs / "product.xyz", product)
    band = interpolate_reaction_path(reactant, product, n_images=N_IMAGES, method="idpp", mic=False)
    write(inputs / "initial-band.extxyz", band)

    viewer = Viewer(band, height=380, look={"labels": False})
    viewer.set_fps(6).play()
    viewer.write_spec(inputs / "initial-band.json", structure_path=inputs / "initial-band.extxyz")
    print(f"wrote {len(band)} images to {inputs}")


if __name__ == "__main__":
    main()
