"""Build the 9 x 9 grid of symmetric stretch and bend geometries of water.

No calculator is used. Both O-H distances vary together from 0.80 to 1.20 Angstrom and
the H-O-H angle from 80 to 160 degrees. The frames are ordered angle-major,
distance-minor, and water-pes-grid.json lists the two axes:

    python water-pes-build.py --output ../models
"""

import argparse
import json
from pathlib import Path

import numpy as np

from atomli import Atoms
from atomli.io import write

DISTANCES = np.linspace(0.8, 1.2, 9)
ANGLES = np.linspace(80, 160, 9)


def water_geometry(distance, angle):
    half = np.radians(angle) / 2
    x, y = distance * np.sin(half), distance * np.cos(half)
    return Atoms("OH2", positions=[[0, 0, 0], [x, y, 0], [-x, y, 0]])


def build(output):
    output.mkdir(parents=True, exist_ok=True)
    frames = [water_geometry(d, a) for a in ANGLES for d in DISTANCES]
    write(output / "water-pes-grid.extxyz", frames)
    (output / "water-pes-grid.json").write_text(json.dumps({
        "bond_lengths_angstrom": DISTANCES.tolist(), "angles_degrees": ANGLES.tolist(),
        "frame_order": "angle-major, distance-minor"}, indent=2) + "\n")
    return frames


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

    viewer = Viewer(frames, height=360, look={"background": "white", "axes": True, "legend": True, "labels": True})
    viewer.set_frame(30)  # 0.95 Angstrom, 110 degrees: the grid minimum
    viewer.write_spec(spec, structure_path=spec.with_name("water-pes-grid.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 for the documentation page")
    args = parser.parse_args()
    frames = build(args.output)
    if args.spec:
        write_figure(frames, args.spec)


if __name__ == "__main__":
    main()
