"""Load the six species of the thiolate and CO2 energy cycles and write them as extxyz.

No calculator is used. The structures are hand-prepared inputs in ../inputs.

    python thiolate-build.py --inputs ../inputs --output ../models
"""

import argparse
from pathlib import Path

from atomli.io import read, write

SPECIES = ("benzyl_thiolate", "benzyl_monothiocarbonate", "co2", "benzyl_mercaptan", "h2s", "hs_anion")


def load_molecule(filename):
    atoms = read(filename)
    atoms.set_pbc(False)
    atoms.set_positions(atoms.get_positions() - atoms.get_positions().mean(axis=0))
    return atoms


def build(inputs, output):
    output.mkdir(parents=True, exist_ok=True)
    structures = {name: load_molecule(inputs / f"{name}.xyz") for name in SPECIES}
    for name, atoms in structures.items():
        write(output / f"thiolate-{name.replace('_', '-')}-start.extxyz", atoms)
    return structures


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

    viewer = Viewer([adduct], height=360, look={"background": "white", "axes": True, "legend": True, "labels": False})
    viewer.write_spec(spec, structure_path=spec.with_name("thiolate-adduct-start.extxyz"))


def main():
    here = Path(__file__).resolve().parent
    parser = argparse.ArgumentParser()
    parser.add_argument("--inputs", type=Path, default=here.parent / "inputs")
    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()
    structures = build(args.inputs, args.output)
    if args.spec:
        write_figure(structures["benzyl_monothiocarbonate"], args.spec)


if __name__ == "__main__":
    main()
