"""Tutorial — Does cold MoS2 break at a higher stress?

Faiyad et al., Friction 13, 9441020 (2025), Fig. 3: monolayer MoS2 stretched at 100, 200 and 300 K
with reactive MD (ReaxFF) fails at a higher stress when colder. That temperature dependence is one
step in the paper's explanation of why MoS2 lubricant debris is smaller in the cold.

This version repeats the test with an ML potential (MACE-MP-0 by default, no extra files needed):
  1. build a rectangular monolayer MoS2 cell (~144 atoms)
  2. thermalize at temperature T with a Langevin thermostat
  3. stretch it in small strain increments along one direction, relaxing with MD after each
  4. record the normal stress; the peak marks failure

Run:   python fracture_temperature.py --direction zigzag          (~5-10 min on a laptop CPU)
Output: out/fracture_<direction>.png, out/fracture_<direction>.csv
Stress is reported in GPa using an effective monolayer thickness of 6.15 Å (the MoS2 interlayer spacing).
"""
import argparse
import sys
from pathlib import Path

import numpy as np
from ase import units
from ase.build import make_supercell, mx2
from ase.md.langevin import Langevin
from ase.md.velocitydistribution import MaxwellBoltzmannDistribution

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)
EV_A3_TO_GPA = 160.21766


def rectangular_monolayer(nx=6, ny=4, vacuum=8.0):
    hexcell = mx2("MoS2", kind="2H", a=3.18, thickness=3.19, size=(1, 1, 1), vacuum=vacuum)
    rect = make_supercell(hexcell, [[1, 0, 0], [1, 2, 0], [0, 0, 1]])  # a x a*sqrt(3): x = zigzag, y = armchair
    rect = rect.repeat((nx, ny, 1))
    rect.pbc = True
    return rect


def pull(T, axis, calc, d_eps=0.01, max_eps=0.45, steps=60, seed=0):
    atoms = rectangular_monolayer()
    atoms.calc = calc
    rng = np.random.default_rng(seed)
    MaxwellBoltzmannDistribution(atoms, temperature_K=T, rng=rng)
    dyn = Langevin(atoms, 1.0 * units.fs, temperature_K=T, friction=0.05, rng=rng)
    dyn.run(400)  # thermalize
    lz = atoms.cell[2, 2]
    strains, stresses = [], []
    eps = 0.0
    while eps < max_eps:
        cell = atoms.cell.array.copy()
        cell[axis] *= 1 + d_eps  # stretch by one increment; total strain eps = (1 + d_eps)^n - 1
        atoms.set_cell(cell, scale_atoms=True)
        eps = (1 + eps) * (1 + d_eps) - 1
        sig = []
        for _ in range(steps // 10):
            dyn.run(10)
            sig.append(atoms.get_stress(voigt=True)[axis])  # ASE convention: tensile stress is positive
        s = np.mean(sig[len(sig) // 2:]) * EV_A3_TO_GPA * lz / 6.15
        strains.append(eps)
        stresses.append(s)
        print(f"T={T:4.0f} K  strain={eps:5.3f}  stress={s:6.2f} GPa", flush=True)
        if len(stresses) > 4 and s < 0.5 * max(stresses):
            break  # failed: stress collapsed
    return np.array(strains), np.array(stresses)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--model", default="mace-small")
    ap.add_argument("--direction", choices=["zigzag", "armchair"], default="zigzag")
    ap.add_argument("--temps", type=float, nargs="+", default=[100, 200, 300])
    args = ap.parse_args()
    axis = 0 if args.direction == "zigzag" else 1
    calc = get_calc(args.model, dtype="float32")

    import matplotlib
    matplotlib.use("Agg")
    import matplotlib.pyplot as plt
    fig, ax = plt.subplots(figsize=(6, 4))
    colors = {100: "#1f6fa8", 200: "#2e7d5b", 300: "#c2414f"}
    lines = ["T_K,strain,stress_GPa"]
    for T in args.temps:
        e, s = pull(T, axis, calc)
        i = int(np.argmax(s))
        ax.plot(e, s, color=colors.get(int(T), None), lw=2, label=f"{T:.0f} K")
        ax.plot(e[i], s[i], "*", ms=14, color=colors.get(int(T), "k"))
        print(f"==> {T:.0f} K: failure stress {s[i]:.1f} GPa at strain {e[i]:.3f}")
        lines += [f"{T:.0f},{a:.4f},{b:.3f}" for a, b in zip(e, s)]
    (OUT / f"fracture_{args.direction}.csv").write_text("\n".join(lines))
    ax.set_xlabel("Engineering strain")
    ax.set_ylabel("Normal stress (GPa)")
    ax.set_title(f"Monolayer MoS$_2$, {args.direction} tension ({args.model})")
    ax.legend(frameon=False)
    fig.tight_layout()
    fig.savefig(OUT / f"fracture_{args.direction}.png", dpi=160)
    print("wrote", OUT / f"fracture_{args.direction}.png")


if __name__ == "__main__":
    main()
