"""Tutorial — Grow a Ni-doped MoS2 film atom by atom.

Romero Garcia, Faiyad & Martini, Comput. Mater. Sci. 244, 113229 (2024) simulated sputter
deposition of MoS2 with 0, 2, 10 and 15 wt% Ni using reactive MD (ReaxFF), then compressed and
sheared the films. Intermediate Ni (2 and 10 wt%) gave the lowest shear stress.

This laptop/Colab version keeps the deposition idea and swaps ReaxFF for an ML potential:
  1. start from a MoS2 monolayer substrate with its bottom row fixed
  2. drop Mo, S and Ni atoms one at a time onto it, with a few eV of kinetic energy, at the target composition
  3. after each impact run a short MD relaxation with a thermostat on the substrate
  4. measure the film: Ni clustering (Ni–Ni neighbors) and MoS2-like order (Mo with 6 S neighbors)

Run:   python deposit.py --ni-wt 0 10              (~10 min on a GPU for both)
Output: out/film_<wt>.extxyz, out/film_metrics.png
"""
import argparse
import sys
from pathlib import Path

import numpy as np
from ase import Atoms, units
from ase.build import mx2
from ase.constraints import FixAtoms
from ase.io import write
from ase.md.langevin import Langevin
from ase.neighborlist import neighbor_list

sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "common"))
from models import get_calc  # noqa: E402

OUT = Path(__file__).parent / "out"
OUT.mkdir(exist_ok=True)
MASS = {"Mo": 95.95, "S": 32.06, "Ni": 58.69}


def species_sequence(n, ni_wt, rng):
    """Random Mo/S/Ni sequence: Mo:S = 1:2 by atoms, Ni set by weight fraction."""
    m_mos2 = MASS["Mo"] + 2 * MASS["S"]
    x_ni = (ni_wt / MASS["Ni"]) / (ni_wt / MASS["Ni"] + (100 - ni_wt) / m_mos2 * 3)  # atom fraction of Ni
    n_ni = round(n * x_ni)
    rest = n - n_ni
    seq = ["Ni"] * n_ni + ["Mo"] * round(rest / 3) + ["S"] * (rest - round(rest / 3))
    rng.shuffle(seq)
    return seq


def grow(ni_wt, n_atoms, calc, seed=0, ke_eV=4.0, relax_steps=120):
    rng = np.random.default_rng(seed)
    film = mx2("MoS2", kind="2H", a=3.18, thickness=3.19, size=(4, 4, 1), vacuum=0)
    film.cell[2] = [0, 0, 40.0]
    film.pbc = True
    film.set_constraint(FixAtoms(indices=[a.index for a in film if a.position[2] < film.positions[:, 2].min() + 0.5]))
    for k, el in enumerate(species_sequence(n_atoms, ni_wt, rng)):
        top = film.positions[:, 2].max()
        f = rng.random(2)
        xy = f[0] * film.cell[0] + f[1] * film.cell[1]
        film += Atoms(el, positions=[[xy[0], xy[1], top + 4.5]])
        v = film.get_velocities()
        # ASE units (eV, amu, Å) make v = sqrt(2 KE / m) directly; aim straight down
        v[-1] = [0.0, 0.0, -np.sqrt(2 * ke_eV / MASS[el])]
        film.set_velocities(v)
        film.calc = calc
        Langevin(film, 1.0 * units.fs, temperature_K=300, friction=0.02, rng=rng).run(relax_steps)
        if (k + 1) % 20 == 0:
            print(f"Ni {ni_wt:>4.1f} wt%: deposited {k + 1}/{n_atoms}", flush=True)
    return film


def metrics(film):
    s = np.array(film.get_chemical_symbols())
    i, j = neighbor_list("ij", film, {("Mo", "S"): 2.8, ("Ni", "Ni"): 2.8, ("Mo", "Mo"): 0.1, ("S", "S"): 0.1,
                                      ("Ni", "S"): 0.1, ("Mo", "Ni"): 0.1})
    mo = np.where(s == "Mo")[0]
    nS = np.array([np.sum((i == m) & (s[j] == "S")) for m in mo])
    ni = np.where(s == "Ni")[0]
    nNi = np.array([np.sum((i == m) & (s[j] == "Ni")) for m in ni]) if len(ni) else np.array([0])
    return {"frac_Mo_6S": float(np.mean(nS == 6)), "mean_Ni_Ni": float(nNi.mean())}


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--ni-wt", type=float, nargs="+", default=[0, 10])
    ap.add_argument("--n-atoms", type=int, default=90)
    ap.add_argument("--model", default="mace-small")
    a = ap.parse_args()
    calc = get_calc(a.model, dtype="float32")
    res = {}
    for w in a.ni_wt:
        film = grow(w, a.n_atoms, calc)
        write(OUT / f"film_{w:g}.extxyz", film)
        res[w] = metrics(film)
        print(f"Ni {w:g} wt%: {res[w]}")

    import matplotlib
    matplotlib.use("Agg")
    import matplotlib.pyplot as plt
    fig, axs = plt.subplots(1, 2, figsize=(8, 3.4))
    ws = list(res)
    axs[0].bar([f"{w:g}%" for w in ws], [res[w]["frac_Mo_6S"] for w in ws], color="#1f6fa8")
    axs[0].set_ylabel("fraction of Mo with 6 S neighbors")
    axs[1].bar([f"{w:g}%" for w in ws], [res[w]["mean_Ni_Ni"] for w in ws], color="#c2414f")
    axs[1].set_ylabel("mean Ni–Ni neighbors")
    for ax in axs:
        ax.set_xlabel("Ni content (wt%)")
    fig.suptitle("Deposited film structure (includes the substrate)")
    fig.tight_layout()
    fig.savefig(OUT / "film_metrics.png", dpi=160)
    print("wrote", OUT / "film_metrics.png")


if __name__ == "__main__":
    main()
