"""Build the CC3 cage, three guest molecules, and the CO2-in-cage starting model.

No calculator is used. The script writes extxyz inputs for co2-cage-run.py:

    python co2-cage-build.py --inputs ../inputs --output ../models
"""

import argparse
from pathlib import Path

import numpy as np

from atomli import Atoms
from atomli.build import molecule
from atomli.io import read, write


def load_molecule(filename):
    """Read the CIF as an isolated molecule centered on its mean position."""
    atoms = read(filename)
    atoms.set_pbc(False)  # the CIF carries a padding cell
    atoms.set_positions(atoms.get_positions() - atoms.get_positions().mean(axis=0))
    return atoms


def combine(host, guest):
    return Atoms(host.get_chemical_symbols() + guest.get_chemical_symbols(),
                 positions=np.vstack([host.get_positions(), guest.get_positions()]))


def build(inputs, output):
    output.mkdir(parents=True, exist_ok=True)
    host = load_molecule(inputs / "cc3-nodvin-991214-host.cif")
    if len(host) != 168:
        raise ValueError("The CC3 input must contain 168 host atoms")
    write(output / "cc3-host-start.extxyz", host)
    guests = {}
    for name in ("CO2", "CH4", "N2"):
        guest = molecule(name)
        guest.set_positions(guest.get_positions() - guest.get_positions().mean(axis=0))
        write(output / f"cc3-guest-{name.lower()}-start.extxyz", guest)
        guests[name] = guest
    start = combine(host, guests["CO2"])  # the guest sits at the cavity center
    write(output / "cc3-co2-start.extxyz", start)
    return start


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

    colors = ["#b9c0cb"] * 168 + ["#d74737"] * (len(start) - 168)
    viewer = Viewer([start], height=480, look={
        "background": "white", "axes": True, "legend": True, "labels": False,
        "atom_colors": colors,
        "color_legend": {"#b9c0cb": "host (CC3 cage)", "#d74737": "guest (CO₂)"}})
    viewer.write_spec(spec, structure_path=spec.with_name("cc3-co2-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()
    start = build(args.inputs, args.output)
    if args.spec:
        write_figure(start, args.spec)


if __name__ == "__main__":
    main()
