"""Build three ethanol starting conformers by rotating the hydroxyl hydrogen about C-O.

No calculator is used. The atom order is identical in the three structures:

    python ethanol-build.py --output ../models
"""

import argparse
from pathlib import Path

import numpy as np

from atomli.build import molecule
from atomli.io import write

CONFORMERS = (("anti", 0), ("gauche-plus", 120), ("gauche-minus", -120))


def rotate_hydroxyl(rotation):
    """Rotate H3 about the C1-O2 axis by `rotation` degrees (Rodrigues formula)."""
    atoms = molecule("CH3CH2OH")
    positions = atoms.get_positions()
    axis = positions[2] - positions[1]
    axis /= np.linalg.norm(axis)
    vector = positions[3] - positions[2]
    angle = np.radians(rotation)
    positions[3] = (positions[2] + vector * np.cos(angle) + np.cross(axis, vector) * np.sin(angle)
                    + axis * np.dot(axis, vector) * (1 - np.cos(angle)))
    atoms.set_positions(positions)
    return atoms


def build(output):
    output.mkdir(parents=True, exist_ok=True)
    structures = {name: rotate_hydroxyl(rotation) for name, rotation in CONFORMERS}
    for name, atoms in structures.items():
        write(output / f"ethanol-{name}-start.extxyz", atoms)
    return structures


def write_figure(structures, spec):
    from atomli.visualize import Viewer

    viewer = Viewer(list(structures.values()), height=430, look={"background": "white", "axes": True, "legend": True, "labels": False})
    viewer.set_frame(0)
    viewer.write_spec(spec, structure_path=spec.with_name("ethanol-starts.extxyz"))


def main():
    here = Path(__file__).resolve().parent
    parser = argparse.ArgumentParser()
    parser.add_argument("--output", type=Path, default=here.parent / "models")
    parser.add_argument("--spec", type=Path, help="also write the viewer spec (frames: anti, gauche-plus, gauche-minus)")
    args = parser.parse_args()
    structures = build(args.output)
    if args.spec:
        write_figure(structures, args.spec)


if __name__ == "__main__":
    main()
