"""Tutorial 1 — Benchmark a universal ML potential on doped MoS2.

Reproduces the workflow of Faiyad & Martini, JCTC 2026 at laptop scale:
  1. build a pristine MoS2 monolayer supercell
  2. put one dopant on a Mo site, an S site, or between layers (intercalated, bilayer)
  3. relax every structure with the ML potential
  4. compute the dopant formation energy
         E_f = E(doped) - E(pristine) + mu(removed host atom) - mu(dopant)
     with chemical potentials mu from each element's relaxed reference phase
  5. plot E_f per dopant and site

Run:   python benchmark_dopants.py                    (MACE-MP-0 small, ~3 min on a laptop CPU)
       python benchmark_dopants.py --model uma-s-1p1  (the model used in the paper; needs HF token)
Output: out/formation_energies.csv, out/formation_energies.png
"""
import argparse
import csv
import sys
from pathlib import Path

import numpy as np
from ase import Atoms
from ase.build import bulk, molecule, mx2
from ase.constraints import FixSymmetry
from ase.filters import FrechetCellFilter
from ase.optimize import BFGS

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)

# Elemental reference phases for chemical potentials (lattice constants are starting guesses; cells are relaxed).
REF = {
    "Mo": lambda: bulk("Mo", "bcc", a=3.15),
    "S": lambda: Atoms("S2", positions=[[0, 0, 0], [0, 0, 1.89]]),  # S2 molecule (a simple, common reference)
    "Nb": lambda: bulk("Nb", "bcc", a=3.30),
    "Re": lambda: bulk("Re", "hcp", a=2.76, c=4.46),
    "Ta": lambda: bulk("Ta", "bcc", a=3.30),
    "Ti": lambda: bulk("Ti", "hcp", a=2.95, c=4.68),
    "Ru": lambda: bulk("Ru", "hcp", a=2.71, c=4.28),
    "Au": lambda: bulk("Au", "fcc", a=4.08),
    "Cu": lambda: bulk("Cu", "fcc", a=3.61),
    "Ag": lambda: bulk("Ag", "fcc", a=4.09),
    "Li": lambda: bulk("Li", "bcc", a=3.44),
    "Na": lambda: bulk("Na", "bcc", a=4.23),
    "Se": lambda: Atoms("Se2", positions=[[0, 0, 0], [0, 0, 2.17]]),
    "Te": lambda: Atoms("Te2", positions=[[0, 0, 0], [0, 0, 2.56]]),
    "O": lambda: molecule("O2"),
    "N": lambda: molecule("N2"),
    "Cl": lambda: molecule("Cl2"),
    "F": lambda: molecule("F2"),
}
MO_SITE = ["Nb", "Re", "Ta", "Ti", "Ru", "Au", "Cu"]
S_SITE = ["Se", "Te", "O", "N", "Cl", "F"]
INTERCAL = ["Li", "Na", "Cu", "Ag"]


def relax(atoms, calc, cell=False, fmax=0.05, steps=300):
    atoms = atoms.copy()
    atoms.calc = calc
    target = FrechetCellFilter(atoms) if cell else atoms
    BFGS(target, logfile=None).run(fmax=fmax, steps=steps)
    return atoms


def mu(el, calc, cache={}):
    """Chemical potential = energy per atom of the relaxed elemental reference."""
    if el not in cache:
        ref = REF[el]()
        periodic = ref.pbc.any()
        if not periodic:
            ref.center(vacuum=8.0)
            ref.pbc = True
        r = relax(ref, calc, cell=periodic)
        cache[el] = r.get_potential_energy() / len(r)
    return cache[el]


def monolayer(n=4):
    a = mx2("MoS2", kind="2H", a=3.18, thickness=3.19, size=(n, n, 1), vacuum=8.0)
    a.pbc = True
    return a


def bilayer(n=4, gap=6.15):
    top = monolayer(n)
    bot = top.copy()
    top.translate([0, 0, gap])
    both = bot + top
    both.cell[2, 2] = top.positions[:, 2].max() + 8.0
    both.center(axis=2)
    return both


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--model", default="mace-small")
    ap.add_argument("--size", type=int, default=4, help="n x n supercell")
    args = ap.parse_args()
    calc = get_calc(args.model)

    rows = []
    # --- pristine monolayer and substitutions -------------------------------------------
    pristine = relax(monolayer(args.size), calc)
    E0 = pristine.get_potential_energy()
    mo_idx = next(i for i, s in enumerate(pristine.get_chemical_symbols()) if s == "Mo")
    s_idx = next(i for i, s in enumerate(pristine.get_chemical_symbols()) if s == "S")
    for site, idx, host, dopants in (("Mo-sub", mo_idx, "Mo", MO_SITE), ("S-sub", s_idx, "S", S_SITE)):
        for el in dopants:
            d = pristine.copy()
            d[idx].symbol = el
            d = relax(d, calc)
            Ef = d.get_potential_energy() - E0 + mu(host, calc) - mu(el, calc)
            rows.append((el, site, Ef))
            print(f"{site:9s} {el:3s}  E_f = {Ef:7.3f} eV", flush=True)

    # --- intercalation in a bilayer --------------------------------------------------------
    bil = relax(bilayer(args.size), calc)
    Eb = bil.get_potential_energy()
    z_mid = bil.positions[:, 2].mean()
    xy = bil.cell[0, :2] * 0.5 + bil.cell[1, :2] * 0.5 / 3
    for el in INTERCAL:
        d = bil + Atoms(el, positions=[[xy[0], xy[1], z_mid]])
        d = relax(d, calc)
        Ef = d.get_potential_energy() - Eb - mu(el, calc)
        rows.append((el, "intercalated", Ef))
        print(f"{'intercal':9s} {el:3s}  E_f = {Ef:7.3f} eV", flush=True)

    with open(OUT / "formation_energies.csv", "w", newline="") as f:
        w = csv.writer(f)
        w.writerow(["dopant", "site", "E_f_eV", "model"])
        for r in rows:
            w.writerow([*r[:2], f"{r[2]:.4f}", args.model])

    import matplotlib
    matplotlib.use("Agg")
    import matplotlib.pyplot as plt
    colors = {"Mo-sub": "#1f6fa8", "S-sub": "#d9a20b", "intercalated": "#c2414f"}
    fig, ax = plt.subplots(figsize=(9, 4))
    labels = [f"{e}\n{s.split('-')[0] if s != 'intercalated' else 'int'}" for e, s, _ in rows]
    ax.bar(range(len(rows)), [r[2] for r in rows], color=[colors[r[1]] for r in rows])
    ax.set_xticks(range(len(rows)), labels, fontsize=8)
    ax.axhline(0, color="k", lw=0.8)
    ax.set_ylabel("Formation energy (eV)")
    ax.set_title(f"Dopant formation energies in MoS$_2$ ({args.model})")
    for k, c in colors.items():
        ax.bar([], [], color=c, label=k)
    ax.legend(frameon=False, fontsize=8)
    fig.tight_layout()
    fig.savefig(OUT / "formation_energies.png", dpi=160)
    print("wrote", OUT / "formation_energies.png")


if __name__ == "__main__":
    main()
