"""SN2 Cl- + CH3Cl, build stage: the two ion-dipole complexes and the initial band.

Constructs the reactant complex Cl(a)-...CH3-Cl(b) and the product complex
Cl(a)-CH3...Cl(b(-)) (the same complex with the roles of the two chlorides
exchanged) and an IDPP interpolation between them. Labels are fixed: atom 0 is
carbon, 1-3 hydrogen, 4 the chloride that attacks (Cl a), 5 the chloride that
leaves (Cl b). No calculator is attached and no energy is computed. Writes
inputs for sn2-neb-run.py.

    python sn2-neb-build.py --output ../../studies/sn2-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_CH = 1.09        # angstrom, starting C-H distance
ANGLE_CLCH = 108.0 # degrees, starting Cl-C-H angle in the bonded CH3Cl
R_BOND = 1.78      # angstrom, starting C-Cl in the bonded CH3Cl
R_FREE = 3.20      # angstrom, starting C...Cl- in the complex
N_IMAGES = 15      # frames in the band, endpoints included


def complex_(bonded):
    """C3v complex along z. `bonded` is 'b' (reactant, Cl b attached) or 'a' (product)."""
    rho = R_CH * np.sin(np.radians(ANGLE_CLCH))
    height = R_CH * np.cos(np.radians(ANGLE_CLCH))        # H height, toward the free chloride
    sign = -1.0 if bonded == "b" else 1.0
    hydrogens = [[rho * np.cos(a), rho * np.sin(a), sign * height] for a in np.radians([0, 120, 240])]
    if bonded == "b":
        cl_a, cl_b = [0, 0, -R_FREE], [0, 0, R_BOND]
    else:
        cl_a, cl_b = [0, 0, -R_BOND], [0, 0, R_FREE]
    return Atoms("CH3Cl2", positions=[[0, 0, 0]] + hydrogens + [cl_a, cl_b])


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 = complex_("b"), complex_("a")
    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()
