"""Helpers shared by the molten-salt tutorials: random melt builder, RDFs, Kirkwood–Buff integrals."""
import numpy as np
from ase import Atoms

MASS = {"Li": 6.94, "K": 39.098, "Na": 22.99, "Fe": 55.845, "Cl": 35.45}


def random_melt(counts: dict, density_g_cm3: float, seed=0, dmin=2.0):
    """Place ions randomly in a cubic box at the target density, keeping a minimum separation."""
    rng = np.random.default_rng(seed)
    syms = [s for s, n in counts.items() for _ in range(n)]
    mass = sum(MASS[s] for s in syms) / 6.02214076e23  # g
    L = (mass / density_g_cm3) ** (1 / 3) * 1e8  # Å
    pos = []
    for s in syms:
        for _ in range(20000):
            p = rng.random(3) * L
            if all(np.linalg.norm((p - q) - L * np.round((p - q) / L)) > dmin for q in pos):
                pos.append(p)
                break
        else:
            raise RuntimeError("could not place ion; lower density or dmin")
    order = rng.permutation(len(syms))
    return Atoms([syms[i] for i in order], positions=np.array(pos)[order], cell=[L] * 3, pbc=True)


def partial_rdf(frames, a, b, rmax=None, nbins=200):
    """g_ab(r) averaged over frames (cubic or orthorhombic cells, minimum image)."""
    L = frames[0].cell.lengths()
    rmax = rmax or 0.5 * L.min()
    edges = np.linspace(0, rmax, nbins + 1)
    hist = np.zeros(nbins)
    na = nb = 0
    for f in frames:
        s = np.array(f.get_chemical_symbols())
        A, B = f.positions[s == a], f.positions[s == b]
        d = A[:, None, :] - B[None, :, :]
        d -= f.cell.lengths() * np.round(d / f.cell.lengths())
        r = np.linalg.norm(d, axis=-1)
        if a == b:
            r = r[np.triu_indices(len(A), 1)]
        hist += np.histogram(r.ravel(), edges)[0]
        na, nb, vol = len(A), len(B), f.get_volume()
    pairs = na * (na - 1) / 2 if a == b else na * nb
    shell = 4 / 3 * np.pi * (edges[1:] ** 3 - edges[:-1] ** 3)
    g = hist / len(frames) / (pairs / vol * shell)
    return 0.5 * (edges[1:] + edges[:-1]), g


def coordination(r, g, rho_b, rcut):
    m = r <= rcut
    return 4 * np.pi * rho_b * np.trapezoid(g[m] * r[m] ** 2, r[m])


def kb_running(r, g):
    """Running Kirkwood–Buff integral G(R) = 4 pi ∫_0^R (g(r) - 1) r^2 dr  (Å^3)."""
    integrand = 4 * np.pi * (g - 1) * r ** 2
    return np.concatenate([[0], np.cumsum(0.5 * (integrand[1:] + integrand[:-1]) * np.diff(r))])
