"""Tutorial — Let the model tell you which structures to label next.

Active learning grows a training set only where the ML potential is unsure. The in-preparation
work (HER-AL) adds a bias force that pushes MD toward high-uncertainty configurations, labels
those with DFT, retrains, and repeats.

This tutorial builds the core of that loop with two pretrained models as a "committee":
  1. run short MD of water on a Pt(111) slab with MACE-MP-0 small
  2. re-evaluate every saved frame with MACE-MP-0 medium
  3. uncertainty = largest per-atom force disagreement between the two models
  4. pick the most uncertain, mutually distinct frames and write them out for DFT labeling

Run:   python committee_selection.py            (~3 min on a GPU)
Output: out/uncertainty.png, out/to_label.extxyz (frames you would send to DFT)
"""
import argparse
import sys
from pathlib import Path

import numpy as np
from ase import Atoms, units
from ase.build import fcc111, molecule
from ase.constraints import FixAtoms
from ase.io import write
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)


def pt_water(n_water=10, seed=0):
    slab = fcc111("Pt", size=(3, 3, 4), vacuum=0.0, a=3.92)
    top = slab.positions[:, 2].max()
    slab.cell[2, 2] = top + 14.0
    rng = np.random.default_rng(seed)
    placed = []
    for _ in range(n_water):
        for _ in range(500):
            p = rng.random(3) * [1, 1, 0] @ slab.cell + [0, 0, top + 2.3 + rng.random() * 7]
            if all(np.linalg.norm(p - q) > 2.8 for q in placed):
                placed.append(p)
                break
        w = molecule("H2O")
        w.rotate(rng.random() * 360, rng.normal(size=3))
        w.translate(p - w.positions[0])
        slab += w
    slab.set_constraint(FixAtoms(indices=[a.index for a in slab if a.symbol == "Pt" and a.position[2] < 2.5]))
    slab.pbc = True
    return slab


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--steps", type=int, default=3000, help="0.5 fs steps")
    ap.add_argument("--T", type=float, default=350)
    ap.add_argument("--n-select", type=int, default=5)
    args = ap.parse_args()

    atoms = pt_water()
    atoms.calc = get_calc("mace-small", dtype="float32")
    MaxwellBoltzmannDistribution(atoms, temperature_K=args.T, rng=np.random.default_rng(0))
    dyn = Langevin(atoms, 0.5 * units.fs, temperature_K=args.T, friction=0.02, rng=np.random.default_rng(1))
    frames, f_small = [], []
    for i in range(0, args.steps, 25):
        dyn.run(25)
        frames.append(atoms.copy())
        f_small.append(atoms.get_forces().copy())

    judge = get_calc("mace-medium", dtype="float32")
    sigma = []
    for fr, fs in zip(frames, f_small):
        fr.calc = judge
        dev = np.linalg.norm(fr.get_forces() - fs, axis=1)
        sigma.append(dev.max())
    sigma = np.array(sigma)

    # greedy pick: most uncertain first, skipping frames within 4 saves of an earlier pick (diversity)
    order, picked = np.argsort(sigma)[::-1], []
    for k in order:
        if all(abs(k - j) > 4 for j in picked):
            picked.append(int(k))
        if len(picked) == args.n_select:
            break
    for k in picked:
        frames[k].info["max_force_dev_eV_A"] = float(sigma[k])
        frames[k].calc = None
    write(OUT / "to_label.extxyz", [frames[k] for k in sorted(picked)])
    print("max force disagreement (eV/Å): median %.3f, max %.3f" % (np.median(sigma), sigma.max()))
    print("frames selected for DFT labeling:", sorted(picked))

    import matplotlib
    matplotlib.use("Agg")
    import matplotlib.pyplot as plt
    t = np.arange(len(sigma)) * 25 * 0.5e-3
    fig, ax = plt.subplots(figsize=(6.5, 3.6))
    ax.plot(t, sigma, color="#1f6fa8", lw=1.5)
    ax.plot(t[picked], sigma[picked], "o", color="#c2414f", label="selected for DFT")
    ax.set_xlabel("Time (ps)")
    ax.set_ylabel("max |ΔF| small vs medium (eV/Å)")
    ax.set_title("Committee disagreement along Pt(111)–water MD")
    ax.legend(frameon=False)
    fig.tight_layout()
    fig.savefig(OUT / "uncertainty.png", dpi=160)
    print("wrote", OUT / "uncertainty.png")


if __name__ == "__main__":
    main()
