"""Extras 1 + 2: animation-ready phonon modes and mode-linked Gamma_II relaxation contributions.

Reads the deposited recompute release laid out as RELEASE/inputs/<salt>/... and RELEASE/code/ (rebuild that layout from
the Borealis files with scripts/rebuild_release_layout.py). Physics comes only from the deposited code: t1_gamma2_core.py
(ion_hamiltonian, coupling_operators, spin_flip_rates, lebedev14, gamma2_powder) and t1_recompute.py (cluster_modes,
dense_grid). This script only enumerates the same modes with their identities and splits the same powder-averaged rate
into ordered phonon pairs.

    python export_modes_pairs.py RELEASE OUTDIR [SALT ...]

Writes OUTDIR/modes/<salt>/... and OUTDIR/contributions/<salt>/... (one folder per salt so salts can run in parallel);
scripts/merge_tables.py concatenates the per-salt tables.
"""
import csv
import itertools
import json
import math
import sys
import time
from pathlib import Path

import numpy as np

EXPORTER_VERSION = "1.0.0"
RELEASE, OUT = Path(sys.argv[1]).resolve(), Path(sys.argv[2]).resolve()
sys.path.insert(0, str(RELEASE / "code"))
import t1_recompute as tr  # noqa: E402
from t1_gamma2_core import (coupling_operators, gamma2_powder, ion_hamiltonian, lebedev14,  # noqa: E402
                            mode_mean_square_q, spin_flip_rates, translations)

PRIORITY = ["SEED", "R3_F", "R4_pCl", "R4_pBr", "R5_pI"]
SIGMAS = [2.0, 3.0, 5.0, 7.0, 10.0, 15.0, 20.0, 30.0]
FIELD, TEMP, CUT, MIN_WIDTH = tr.FIELD, tr.TEMPS[0], tr.CUT, 21.0
assert (FIELD, TEMP, CUT) == (0.345, 300.0, 500.0)
N_TOP = {"gamma": 300, "dense": 1000}  # ordered pairs exported per condition (>= the 200 requested)
HEAT_KEEP = 1e-9       # heatmap cells below this fraction of the total are dropped; their sum is reported
HEAT_BIN = 5.0         # cm-1, frequency-pair heatmap bin width
MIS_EDGES = np.concatenate([np.arange(0.0, 150.0 + 1e-9, 0.5), [np.inf]])  # |w_abs - w_emit| bins (cm-1)
DEGEN_TOL = 1e-3       # cm-1: modes at the same q closer than this form a degeneracy group
VIS_MAX_DISP = 0.25    # Angstrom: largest atomic displacement in the shipped XYZ animations
N_FRAMES = 20
FAMILY_PARENT = [154, 155, 156, 157]  # parent Gamma bands targeted by the campaign (validator 'designed_modes')
SALTS = sys.argv[3:] or PRIORITY


def sha256(path) -> str:
    import hashlib
    return hashlib.sha256(Path(path).read_bytes()).hexdigest()


def fmt(x):
    return repr(float(x)) if x is not None else ""


# ----------------------------------------------------------------------------------------------- mode enumeration

def enumerate_modes(ph, man, grid):
    """t1_recompute.cluster_modes with every mode's identity kept: the same loop, order, exclusions and vectors, plus
    (q index, band, part, complex lattice-phase eigenvector) and the excluded-mode tally."""
    cell, frac = ph.primitive.cell, ph.primitive.scaled_positions
    masses = np.array(man["masses_amu"])
    rot = np.array(man["frame"]["rotation_rows_new_axes"])
    catoms = [a["cell_atom"] for a in man["atoms"]]
    metal = catoms[man["metal_index"]]
    pos = frac[metal] @ cell + np.array(man["positions_angstrom"]) @ rot
    off = np.linalg.solve(cell.T, (pos - frac[catoms] @ cell).T).T
    assert np.abs(off - off.round()).max() < 2e-3
    off = off.round()
    rows = np.ravel([[3 * c, 3 * c + 1, 3 * c + 2] for c in catoms])
    t = translations(masses)
    ncell = int(np.prod(grid))
    seen, modes, excluded = set(), [], []
    for idx in itertools.product(*(range(n) for n in grid)):
        q = np.array(idx, dtype=float) / grid
        key, mkey = tuple(np.round(q % 1, 6) % 1), tuple(np.round(-q % 1, 6) % 1)
        if mkey in seen:
            continue
        seen.add(key)
        ph.dynamical_matrix.run(q)
        dm = ph.dynamical_matrix.dynamical_matrix
        p = np.repeat(np.exp(2j * np.pi * frac @ q), 3)
        dl = p[:, None] * dm * p.conj()[None, :]
        real_q = key == mkey
        w2, v = np.linalg.eigh(dl.real if real_q else dl)
        f = np.sign(w2) * np.sqrt(np.abs(w2)) * ph.unit_conversion_factor * tr.THZ_TO_CM1
        lat = np.repeat(np.exp(2j * np.pi * off @ q), 3)
        acoustic = set(np.argsort(np.abs(w2))[:3]) if not any(idx) else set()
        for m in range(len(f)):
            nparts = 1 if real_q else 2
            if m in acoustic:
                excluded.append(dict(q=list(idx), band=m, freq=float(f[m]), reason="gamma_acoustic", n_standing_waves=nparts))
                continue
            if f[m] <= 0:
                excluded.append(dict(q=list(idx), band=m, freq=float(f[m]), reason="imaginary_or_zero", n_standing_waves=nparts))
                continue
            if f[m] > CUT:
                continue  # above the 500 cm-1 cutoff (not listed individually)
            e = v[rows, m] * lat / np.sqrt(ncell)
            for part, vec in (([("re", e.real)]) if real_q else [("cos", np.sqrt(2) * e.real), ("sin", np.sqrt(2) * e.imag)]):
                modes.append(dict(q=tuple(idx), band=m, part=part, freq=float(f[m]), vec=vec, eig=v[:, m].copy(), real_q=real_q))
    vecs = np.array([m["vec"] for m in modes])
    vecs = vecs - (vecs @ t) @ t.T
    vecs = (vecs.reshape(len(vecs), -1, 3) @ rot.T).reshape(len(vecs), -1)
    for m, x in zip(modes, vecs):
        m["vec"] = x
    return modes, excluded, off.astype(int)


def gamma_stored_modes(ph, man, cpl):
    """The Gamma modes of a stored couplings file (the campaign T1 tool's set), matched to phonopy Gamma bands by index.
    Returns the modes in the file's row order with the phonopy eigenvector, sign-aligned to the manifest's vector."""
    modes, excluded, off = enumerate_modes(ph, man, np.array([1, 1, 1]))
    by_band = {m["band"]: m for m in modes}
    idx, fr = cpl["modes"]["indices"], cpl["modes"]["frequencies_cm1"]
    mvec = {b: np.array(v) for b, v in zip(man["modes"]["indices"], man["modes"]["vectors_mass_weighted"])}
    out = []
    for b, f in zip(idx, fr):
        if b in by_band:
            m = dict(by_band[b])
        else:  # above 500 cm-1 (validator's extended set): rebuild the same way
            m = gamma_mode_above_cut(ph, man, b, off)
        assert abs(m["freq"] - f) < 0.02, (b, m["freq"], f)
        m["freq_stored"] = float(f)
        if b in mvec:  # sign/rotation check against the vector the campaign projected
            ov = float(m["vec"] @ mvec[b]) / (np.linalg.norm(m["vec"]) * np.linalg.norm(mvec[b]))
            m["overlap_with_campaign_vector"] = ov
            if ov < 0:
                m["vec"], m["eig"] = -m["vec"], -m["eig"]
        out.append(m)
    return out, excluded


def gamma_mode_above_cut(ph, man, band, off):
    frac = ph.primitive.scaled_positions
    masses = np.array(man["masses_amu"])
    rot = np.array(man["frame"]["rotation_rows_new_axes"])
    rows = np.ravel([[3 * a["cell_atom"], 3 * a["cell_atom"] + 1, 3 * a["cell_atom"] + 2] for a in man["atoms"]])
    ph.dynamical_matrix.run([0, 0, 0])
    w2, v = np.linalg.eigh(ph.dynamical_matrix.dynamical_matrix.real)
    f = np.sign(w2) * np.sqrt(np.abs(w2)) * ph.unit_conversion_factor * tr.THZ_TO_CM1
    t = translations(masses)
    x = v[rows, band].real.copy()
    x = x - (x @ t) @ t.T
    x = (x.reshape(-1, 3) @ rot.T).ravel()
    return dict(q=(0, 0, 0), band=band, part="re", freq=float(f[band]), vec=x, eig=v[:, band].copy(), real_q=True)


# ----------------------------------------------------------------------------------------------- descriptors

def fold_angles(el, pos):
    """Both dithiolene folds (deg) with the deposited definition (structures.fold_frame): angle between the S-V-S plane
    normal and the best plane through S,S and their nearest C atoms, for each chelating S pair bridged by a C=C bond."""
    v = pos[el == "V"][0]
    sidx = [i for i in np.where(el == "S")[0] if np.linalg.norm(pos[i] - v) < 2.7]
    carbon = pos[el == "C"]
    out = []
    for i, j in itertools.combinations(sidx, 2):
        a, b = pos[i], pos[j]
        c, d = [min(carbon, key=lambda p: np.linalg.norm(p - s)) for s in (a, b)]
        if not 1.0 < np.linalg.norm(c - d) < 1.65:
            continue
        n1 = np.cross(a - v, b - v); n1 /= np.linalg.norm(n1)
        n2 = np.linalg.svd(np.array([a, b, c, d]) - np.mean([a, b, c, d], axis=0))[2][-1]
        out.append(((i, j), math.degrees(math.acos(min(1.0, abs(float(n1 @ n2)))))))
    return sorted(out)


def descriptors(el, pos, masses, x, freq):
    """Motion descriptors of a cluster vector x (mass-weighted, metal frame) per unit normal coordinate Q (amu^1/2 A)."""
    u = (x.reshape(-1, 3) / np.sqrt(masses)[:, None])
    iv = int(np.where(el == "V")[0][0]); io = int(np.where(el == "O")[0][0])
    donors = [i for i in np.where(el == "S")[0] if np.linalg.norm(pos[i] - pos[iv]) < 2.7]
    rvo = pos[io] - pos[iv]; nvo = rvo / np.linalg.norm(rvo)
    duo = u[io] - u[iv]
    d_vo = float(duo @ nvo)
    tilt = float(np.linalg.norm(duo - (duo @ nvo) * nvo) / np.linalg.norm(rvo))  # rad per unit Q
    d_vs = []
    for i in donors:
        r = pos[i] - pos[iv]
        d_vs.append(float((u[i] - u[iv]) @ (r / np.linalg.norm(r))))
    h = 1e-3
    fp, fm = fold_angles(el, pos + h * u), fold_angles(el, pos - h * u)
    dfold = [(a[1] - b[1]) / (2 * h) for a, b in zip(fp, fm)]
    shell = [iv, io] + donors
    q_rms = math.sqrt(mode_mean_square_q(freq, TEMP))
    return dict(dR_VO_per_Q=d_vo, VO_tilt_rad_per_Q=tilt, dR_VS_per_Q=d_vs, dfold_deg_per_Q=dfold,
                first_shell_weight=float((x.reshape(-1, 3)[shell] ** 2).sum()), cluster_weight=float(x @ x), Q_rms_300K=q_rms)


def describe(d, w_anion_cell):
    """Short evidence-based label from the descriptors at the 300 K rms amplitude (thresholds documented in README)."""
    q = d["Q_rms_300K"]
    parts = []
    if w_anion_cell is not None and w_anion_cell < 0.2:
        parts.append("mainly cation/lattice motion")
    vs = np.array(d["dR_VS_per_Q"]) * q
    if abs(d["dR_VO_per_Q"] * q) > 0.003:
        parts.append(f"V=O stretch ({d['dR_VO_per_Q'] * q:+.4f} A at 300 K rms)")
    if d["VO_tilt_rad_per_Q"] * q > math.radians(0.5):
        parts.append(f"V=O tilt ({math.degrees(d['VO_tilt_rad_per_Q'] * q):.2f} deg)")
    if np.abs(vs).max() > 0.003:
        sym = "symmetric" if np.all(np.sign(vs[np.abs(vs) > 0.3 * np.abs(vs).max()]) == np.sign(vs[np.argmax(np.abs(vs))])) else "antisymmetric"
        parts.append(f"{sym} V-S stretch (max {np.abs(vs).max():.4f} A)")
    fold = np.abs(np.array(d["dfold_deg_per_Q"])) * q
    if len(fold) and fold.max() > 0.5:
        parts.append(f"dithiolene fold ({', '.join(f'{x:.2f}' for x in fold)} deg)")
    if not parts:
        parts.append("small first-shell motion" if d["first_shell_weight"] < 0.05 else "first-shell bend/deformation")
    return "; ".join(parts)


def molecule_ids(symbols, cell, frac):
    """Connected components of the cell (covalent radii x 1.15, minimum image); anions = components containing V."""
    from ase import Atoms
    from ase.neighborlist import natural_cutoffs, neighbor_list
    from scipy.sparse import coo_matrix
    from scipy.sparse.csgraph import connected_components
    at = Atoms(symbols=symbols, cell=cell, scaled_positions=frac, pbc=True)
    i, j = neighbor_list("ij", at, natural_cutoffs(at, mult=1.15))
    n, lab = connected_components(coo_matrix((np.ones(len(i)), (i, j)), shape=(len(at), len(at))))
    anion = np.array([any(symbols[k] == "V" for k in np.where(lab == lab[a])[0]) for a in range(len(at))])
    return lab, anion


# ----------------------------------------------------------------------------------------------- pair rates

def powder_pairs(v0, h0, ops, freqs, sigma, d):
    """gamma2_powder with W_down and W_up kept apart: per-orientation eigenbasis, spin_flip_rates, Lebedev-14 weights."""
    dirs, wts = lebedev14()
    n = len(freqs)
    down, up = np.zeros((n, n)), np.zeros((n, n))
    for nv, wt in zip(dirs, wts):
        e, u = np.linalg.eigh(ion_hamiltonian(v0, h0, FIELD * np.asarray(nv, dtype=float), d))
        vm = np.einsum("ji,ajk,kl->ail", u.conj(), ops, u)
        r = spin_flip_rates(e, vm, freqs, [TEMP], sigma)
        down += wt * r["down"][0]
        up += wt * r["up"][0]
    return down, up


# ----------------------------------------------------------------------------------------------- main per salt

def load_json(p):
    return json.loads(Path(p).read_text())


def run_salt(salt, dep_index):
    t0 = time.time()
    import phonopy
    base = RELEASE / "inputs" / salt
    files = load_json(base / "inputs.json")["files"]
    ph = phonopy.load(str(base / "phonopy_params.yaml"))
    symbols = list(ph.primitive.symbols)
    cell, frac = ph.primitive.cell, ph.primitive.scaled_positions
    lab, anion = molecule_ids(symbols, cell, frac)
    mdir, cdir = OUT / "modes" / salt, OUT / "contributions" / salt
    mdir.mkdir(parents=True, exist_ok=True); cdir.mkdir(parents=True, exist_ok=True)
    src = lambda rel: dict(release_path=f"inputs/{salt}/{rel}", sha256=sha256(base / rel), **dep_index.get(f"inputs/{salt}/{rel}", {}))  # noqa: E731
    phon_sha = sha256(base / "phonopy_params.yaml")
    structure_id = f"{salt}:phonopy:{phon_sha[:12]}"

    sets = []  # (sampling, coupling_set, couplings file, manifest file, grid)
    dense_c, dense_m = files["couplings_dense"]["file"], files["displacement_manifest_dense"]["file"]
    sets.append(("gamma", "main", dense_c, dense_m, [1, 1, 1]))
    sets.append(("dense", "main", dense_c, dense_m, tr.dense_grid(ph, MIN_WIDTH).tolist()))
    if files["couplings_judged"]["sha256"] != files["couplings_dense"]["sha256"]:
        sets.append(("gamma", "validator_cut800", files["couplings_judged"]["file"], files["displacement_manifest_judged"]["file"], [1, 1, 1]))

    mode_rows, cond_rows, pair_rows, group_rows, marg, heat, mis, checks, anim = [], [], [], [], {}, {}, [], [], {}
    for sampling, cset, cfile, mfile, grid in sets:
        cpl, man = load_json(base / cfile), load_json(base / mfile)
        assert cpl["phonon_set_sha256"] == man["phonon_set_sha256"] == phon_sha, (salt, cset)
        d = int(cpl["d_count"])
        v0, h0 = np.array(cpl["reference"]["V_nevpt2"], dtype=float), np.array(cpl["reference"]["h_soc"], dtype=float)
        glabel = "G111" if sampling == "gamma" else "D" + "".join(map(str, grid))
        if sampling == "gamma":
            modes, excluded = gamma_stored_modes(ph, man, cpl)
            dv = np.array(cpl["mode_couplings"]["dV"], dtype=float); dh = np.array(cpl["mode_couplings"]["dh"], dtype=float)
            # check: the stored mode couplings equal the direction couplings projected on these vectors (sign-aligned)
            mv = np.array([m["vec"] for m in modes]) @ np.array(man["directions_mass_weighted"]).T
            dv_proj = np.einsum("aj,jmn->amn", mv, np.array(cpl["direction_couplings"]["dV"]))
            checks.append(dict(check=f"{salt}/{sampling}/{cset}: stored dV vs projection of direction couplings on exported vectors",
                               max_abs_diff_cm1=float(np.abs(dv_proj - dv).max()), max_abs_dV_cm1=float(np.abs(dv).max())))
        else:
            modes, excluded, _ = enumerate_modes(ph, man, np.array(grid))
            f_ref, v_ref = tr.cluster_modes(ph, man, np.array(grid))  # the deposited function, for identity
            same = np.array_equal(f_ref, np.array([m["freq"] for m in modes])) and np.array_equal(v_ref, np.array([m["vec"] for m in modes]))
            checks.append(dict(check=f"{salt}/{sampling}: enumerated modes identical to t1_recompute.cluster_modes", passed=bool(same), n_modes=len(modes)))
            assert same
            c = np.array([m["vec"] for m in modes]) @ np.array(man["directions_mass_weighted"]).T
            dv = np.einsum("aj,jmn->amn", c, np.array(cpl["direction_couplings"]["dV"]))
            dh = np.einsum("aj,jkmn->akmn", c, np.array(cpl["direction_couplings"]["dh"]))
        freqs = np.array([m["freq"] for m in modes])
        if sampling == "gamma":
            freqs = np.array(cpl["modes"]["frequencies_cm1"], dtype=float)  # the stored values the T1 tool used
        ops = coupling_operators(dv, dh, d)
        n = len(freqs)

        # mode identities + descriptors
        el = np.array(man["symbols"]); cpos = np.array(man["positions_angstrom"]); cm = np.array(man["masses_amu"])
        ids = []
        for k, m in enumerate(modes):
            qs = ".".join(map(str, m["q"]))
            mid = f"{salt}:{glabel}:q{qs}:b{m['band']}:{m['part']}"
            ids.append(mid)
            m["id"] = mid
        groups = {}
        for k, m in enumerate(modes):  # degeneracy groups at the same q (cos/sin of one Bloch wave are always together)
            key = (m["q"],)
            g = groups.setdefault(key, [])
            for gi in g:
                if abs(modes[gi[0]]["freq"] - m["freq"]) < DEGEN_TOL:
                    gi.append(k); break
            else:
                g.append([k])
        dgroup = {}
        for key, gl in groups.items():
            for gi in gl:
                gid = f"{salt}:{glabel}:q{'.'.join(map(str, key[0]))}:g{min(modes[i]['band'] for i in gi)}" + (f"-{max(modes[i]['band'] for i in gi)}" if len({modes[i]['band'] for i in gi}) > 1 else "")
                for i in gi:
                    dgroup[i] = gid
        for k, m in enumerate(modes):
            eig = m["eig"].reshape(-1, 3)
            w_an = float((np.abs(eig[anion]) ** 2).sum())
            de = descriptors(el, cpos, cm, m["vec"], freqs[k])
            scale = math.sqrt(np.prod(grid)) / (1.0 if m["part"] == "re" else math.sqrt(2.0))  # supercell -> single-cell normalisation
            m["desc"], m["w_anion_cell"] = de, w_an
            qfrac = (np.array(m["q"]) / np.array(grid))
            mode_rows.append(dict(
                salt_id=salt, structure_id=structure_id, mode_id=m["id"], mode_set=glabel, sampling=sampling, coupling_set=cset,
                coupling_row=k, q_grid="x".join(map(str, grid)), q_index=".".join(map(str, m["q"])),
                q_frac_reduced=" ".join(fmt(x) for x in qfrac), band_index_0based=m["band"], part=m["part"],
                frequency_cm1=fmt(freqs[k]), frequency_phonopy_cm1=fmt(m["freq"]), bloch_group=f"{salt}:{glabel}:q{'.'.join(map(str, m['q']))}:b{m['band']}",
                degeneracy_group=dgroup[k],
                same_eigenvector_as=(f"{salt}:G111:q0.0.0:b{m['band']}:re" if (sampling == "dense" and not any(m["q"])) else ""),
                w_anion_cell=fmt(w_an), cluster_weight=fmt(de["cluster_weight"]), first_shell_weight=fmt(de["first_shell_weight"]),
                dR_VO_A_per_Q=fmt(de["dR_VO_per_Q"]), VO_tilt_rad_per_Q=fmt(de["VO_tilt_rad_per_Q"]),
                dR_VS_A_per_Q=" ".join(fmt(x) for x in de["dR_VS_per_Q"]), dfold_deg_per_Q=" ".join(fmt(x) for x in de["dfold_deg_per_Q"]),
                Q_rms_300K_amu05A=fmt(de["Q_rms_300K"]), cell_normalization_factor=fmt(scale),
                motion_description=describe(descriptors(el, cpos, cm, m["vec"] * scale, freqs[k]), w_an),
                overlap_with_campaign_vector=fmt(m.get("overlap_with_campaign_vector")) if "overlap_with_campaign_vector" in m else "",
            ))

        gnames = []
        for m in modes:
            g = f"{salt}:{glabel}:q{'.'.join(map(str, m['q']))}:b{m['band']}"
            if g not in gnames:
                gnames.append(g)
        gpos = {g: i for i, g in enumerate(gnames)}
        gidx = [gpos[f"{salt}:{glabel}:q{'.'.join(map(str, m['q']))}:b{m['band']}"] for m in modes]
        ng = len(gnames)
        gfreq = [None] * ng; grep_ = [None] * ng
        for k, m in enumerate(modes):
            if gfreq[gidx[k]] is None:
                gfreq[gidx[k]], grep_[gidx[k]] = freqs[k], m["id"]
        # rates per sigma
        cid_base = f"{salt}|{sampling}|{cset}"
        a_marg, e_marg = {}, {}
        for s in SIGMAS:
            cid = f"{cid_base}|s{s:g}"
            down, up = powder_pairs(v0, h0, ops, freqs, s, d)
            P = down + up
            total = float(P.sum())
            ref = gamma2_powder(v0, h0, ops, freqs, FIELD, [TEMP], s, d) if (sampling == "gamma" or s == 5.0) else None
            if ref is not None:
                checks.append(dict(check=f"{cid}: pair matrix vs deposited gamma2_powder", max_rel_pair_diff=float(np.abs(ref["pairs"][0] - P).max() / P.max()),
                                   rel_total_diff=float(abs(ref["rate"][0] / total - 1))))
            flat = P.ravel()
            order = np.argsort(-flat, kind="stable")
            nz = int((flat > 0).sum())
            top = order[:min(N_TOP[sampling], nz)]
            cum = np.cumsum(flat[top])
            for r, ij in enumerate(top):
                a, b = divmod(int(ij), n)
                pair_rows.append(dict(condition_id=cid, rank=r + 1, mode_id_absorbed=ids[a], mode_id_emitted=ids[b], row_absorbed=a, row_emitted=b,
                                      frequency_absorbed_cm1=fmt(freqs[a]), frequency_emitted_cm1=fmt(freqs[b]),
                                      q_absorbed=".".join(map(str, modes[a]["q"])), q_emitted=".".join(map(str, modes[b]["q"])),
                                      mismatch_cm1=fmt(freqs[a] - freqs[b]), rate_s_1=fmt(P[a, b]), rate_down_s_1=fmt(down[a, b]), rate_up_s_1=fmt(up[a, b]),
                                      fraction_of_total=fmt(P[a, b] / total), cumulative_fraction=fmt(cum[r] / total), reverse_pair_rate_s_1=fmt(P[b, a])))
            captured = float(cum[-1]) if len(cum) else 0.0
            # gauge-invariant view: sum over the standing-wave parts of each Bloch wave (q, band) and over both orders
            bg = np.array([gidx[k] for k in range(n)])
            oh = np.zeros((n, ng)); oh[np.arange(n), bg] = 1.0
            G = oh.T @ P @ oh
            U = np.triu(G + G.T, 1) + np.diag(np.diag(G))
            uf = U.ravel(); uo = np.argsort(-uf, kind="stable")[:min(N_TOP[sampling], int((uf > 0).sum()))]
            ucum = np.cumsum(uf[uo])
            for r, ij in enumerate(uo):
                g1, g2 = divmod(int(ij), ng)
                group_rows.append(dict(condition_id=cid, rank=r + 1, bloch_group_1=gnames[g1], bloch_group_2=gnames[g2],
                                       frequency_1_cm1=fmt(gfreq[g1]), frequency_2_cm1=fmt(gfreq[g2]), representative_mode_1=grep_[g1], representative_mode_2=grep_[g2],
                                       rate_s_1=fmt(uf[ij]), fraction_of_total=fmt(uf[ij] / total), cumulative_fraction=fmt(ucum[r] / total)))
            a_marg[s], e_marg[s] = P.sum(axis=1), P.sum(axis=0)
            # heatmap (ordered pairs on w_abs x w_emit) and |mismatch| histogram, both integrate to the total rate
            fmax = max(CUT, float(freqs.max()))
            edges = np.arange(0.0, math.ceil(fmax / HEAT_BIN) * HEAT_BIN + 1e-9, HEAT_BIN)
            ia = np.clip(np.digitize(freqs, edges) - 1, 0, len(edges) - 2)
            onehot = np.zeros((n, len(edges) - 1)); onehot[np.arange(n), ia] = 1.0
            H = onehot.T @ P @ onehot
            keep = H >= HEAT_KEEP * total
            nzc = np.argwhere(keep)
            heat[cid] = dict(axes="cells [i, j, rate_s_1]: i = bin of the absorbed-mode frequency, j = bin of the emitted-mode frequency (ordered pairs)",
                             bin_edges_cm1=edges.tolist(), cells=[[int(i), int(j), float(H[i, j])] for i, j in nzc], total_rate_s_1=total,
                             kept_cells_sum_s_1=float(H[keep].sum()), dropped_cells_sum_s_1=float(H[~keep].sum()),
                             dropped_rule=f"cells with rate < {HEAT_KEEP:g} x total dropped")
            mism = np.abs(freqs[:, None] - freqs[None, :]).ravel()
            hist = np.histogram(mism, bins=MIS_EDGES, weights=flat)[0]
            cumh = np.cumsum(hist)
            for k in range(len(hist)):
                mis.append(dict(condition_id=cid, abs_mismatch_lo_cm1=fmt(MIS_EDGES[k]), abs_mismatch_hi_cm1=("inf" if np.isinf(MIS_EDGES[k + 1]) else fmt(MIS_EDGES[k + 1])),
                                rate_in_bin_s_1=fmt(hist[k]), cumulative_fraction=fmt(cumh[k] / total)))
            cond_rows.append(dict(
                condition_id=cid, salt_id=salt, structure_id=structure_id, sampling=sampling, coupling_set=cset, q_grid="x".join(map(str, grid)),
                n_modes=n, mode_cutoff_cm1=(CUT if cset == "main" else float(man.get("mode_cutoff_cm1", 800.0))), temperature_K=TEMP, field_T=FIELD, sigma_cm1=s,
                averaging="Lebedev-14 orientation average of rates (6 x 1/15, 8 x 3/40); T1 = 1/<W>",
                rate_total_s_1=fmt(total), rate_down_s_1=fmt(down.sum()), rate_up_s_1=fmt(up.sum()), T1_us_recomputed=fmt(1e6 / total),
                n_ordered_pairs=n * n, n_pairs_nonzero=nz, n_pairs_exported=len(top), captured_fraction=fmt(captured / total),
                n_bloch_groups=ng, n_group_pairs_exported=len(uo), group_pairs_captured_fraction=fmt(ucum[-1] / total if len(ucum) else 0.0),
                omitted_remainder_s_1=fmt(total - captured), omitted_fraction=fmt(1 - captured / total),
                couplings_source=json.dumps(src(cfile)), manifest_source=json.dumps(src(mfile)), phonopy_source=json.dumps(src("phonopy_params.yaml")),
                n_excluded_imaginary=sum(x["n_standing_waves"] for x in excluded if x["reason"] == "imaginary_or_zero"),
                most_negative_excluded_cm1=fmt(min([x["freq"] for x in excluded if x["reason"] == "imaginary_or_zero"], default=None)) if any(x["reason"] == "imaginary_or_zero" for x in excluded) else "",
                exporter_version=EXPORTER_VERSION))
            print(f"{cid}: N={n} T1={1e6 / total:.6f} us top{len(top)} captures {captured / total:.4f} [{time.time() - t0:.0f} s]", flush=True)
        marg[f"{sampling}|{cset}"] = (ids, freqs, a_marg, e_marg, [dgroup[k] for k in range(n)], [mode_rows[-n + k]["bloch_group"] for k in range(n)])
        anim[f"{sampling}|{cset}"] = (modes, freqs, man, grid, excluded)

    # ---- write per-salt outputs
    write_csv(mdir / "mode_index.csv", mode_rows)
    write_csv(cdir / "conditions.csv", cond_rows)
    write_csv(cdir / "top_pairs.csv", pair_rows)
    write_csv(cdir / "top_bloch_group_pairs.csv", group_rows)
    write_csv(cdir / "mismatch_cumulative.csv", mis)
    (cdir / "heatmaps.json").write_text(json.dumps(heat))
    mrows = []
    for key, (ids, freqs, a_m, e_m, dg, bg) in marg.items():
        sampling, cset = key.split("|")
        for k in range(len(ids)):
            row = dict(salt_id=salt, sampling=sampling, coupling_set=cset, mode_id=ids[k], frequency_cm1=fmt(freqs[k]), bloch_group=bg[k], degeneracy_group=dg[k])
            for s in SIGMAS:
                row[f"absorbed_s{s:g}_s_1"] = fmt(a_m[s][k]); row[f"emitted_s{s:g}_s_1"] = fmt(e_m[s][k])
            mrows.append(row)
    write_csv(cdir / "mode_marginals.csv", mrows)
    (mdir / "checks.json").write_text(json.dumps(checks, indent=1))
    write_mode_assets(salt, structure_id, ph, lab, anion, anim, pair_rows, mode_rows, mdir, src)
    print(f"{salt} done in {time.time() - t0:.0f} s", flush=True)


def write_csv(path, rows):
    if not rows:
        return
    with open(path, "w", newline="") as fh:
        w = csv.DictWriter(fh, fieldnames=list(rows[0].keys()))
        w.writeheader(); w.writerows(rows)


# ----------------------------------------------------------------------------------------------- animation assets

def select_modes(salt, sampling, cset, pair_rows, mode_rows, family):
    """Selected for full-cell assets: modes of the top 50 ordered pairs at any sigma, the campaign's family modes, and the
    3 largest per descriptor (V=O stretch, V=O tilt, V-S stretch, fold) at the 300 K rms amplitude."""
    sel = {}
    for r in pair_rows:
        if r["condition_id"].startswith(f"{salt}|{sampling}|{cset}|") and r["rank"] <= 50:
            sel.setdefault(r["mode_id_absorbed"], set()).add("top50_pair"); sel.setdefault(r["mode_id_emitted"], set()).add("top50_pair")
    rows = [m for m in mode_rows if m["sampling"] == sampling and m["coupling_set"] == cset]
    for m in rows:
        if sampling == "gamma" and m["band_index_0based"] in family:
            sel.setdefault(m["mode_id"], set()).add("campaign_family")
        if sampling == "dense" and m["q_index"] == "0.0.0" and m["band_index_0based"] in family:
            sel.setdefault(m["mode_id"], set()).add("campaign_family")
    keyf = {
        "VO_stretch": lambda m: abs(float(m["dR_VO_A_per_Q"])) * float(m["Q_rms_300K_amu05A"]),
        "VO_tilt": lambda m: float(m["VO_tilt_rad_per_Q"]) * float(m["Q_rms_300K_amu05A"]),
        "VS_stretch": lambda m: max(abs(float(x)) for x in m["dR_VS_A_per_Q"].split()) * float(m["Q_rms_300K_amu05A"]),
        "fold": lambda m: max([abs(float(x)) for x in m["dfold_deg_per_Q"].split()] or [0]) * float(m["Q_rms_300K_amu05A"]),
    }
    for name, f in keyf.items():
        for m in sorted(rows, key=f, reverse=True)[:3]:
            sel.setdefault(m["mode_id"], set()).add(f"top3_{name}")
    return sel


def write_mode_assets(salt, structure_id, ph, lab, anion, anim, pair_rows, mode_rows, mdir, src):
    cell, frac, symbols = ph.primitive.cell, ph.primitive.scaled_positions, list(ph.primitive.symbols)
    masses = ph.primitive.masses
    receipt = family_for(salt)
    for key, (modes, freqs, man, grid, excluded) in anim.items():
        sampling, cset = key.split("|")
        fam = FAMILY_PARENT if salt == "SEED" else receipt
        sel = select_modes(salt, sampling, cset, pair_rows, mode_rows, fam)
        catoms = [a["cell_atom"] for a in man["atoms"]]
        metal = catoms[man["metal_index"]]
        rot = np.array(man["frame"]["rotation_rows_new_axes"])
        pos = frac[metal] @ cell + np.array(man["positions_angstrom"]) @ rot
        off = np.linalg.solve(cell.T, (pos - frac[catoms] @ cell).T).T.round().astype(int)
        tag = f"{sampling}_{cset}"
        cluster = dict(
            symbols=man["symbols"], masses_amu=man["masses_amu"], positions_metal_frame_angstrom=man["positions_angstrom"],
            cluster_to_cell_atom_0based=catoms, cluster_lattice_offset=off.tolist(), metal_cluster_index=man["metal_index"],
            rotation_rows_new_axes=man["frame"]["rotation_rows_new_axes"],
            frame_rule="r_metal_frame = R (r_cell_frame - r_V_cell_frame); r_cell_frame(cluster atom i) = (frac[cell_atom_i] + offset_i) @ cell",
            coupling_index_note="Row j of directions_mass_weighted / direction_couplings is a 54-vector over these 18 atoms (x,y,z per atom, metal frame); "
                                "a mode's coupling = sum_j c_j dV_j with c = x_mode . direction_j")
        allm = dict(salt_id=salt, structure_id=structure_id, sampling=sampling, coupling_set=cset, q_grid=grid, cluster=cluster,
                    vector_convention="x = mass-weighted cluster vector (amu^1/2-weighted, metal frame, rigid translations projected out), exactly the row "
                                      "the couplings were projected on; displacement per unit normal coordinate Q (amu^1/2 A) is u_i = x_i / sqrt(m_i) in A",
                    modes=[dict(mode_id=m["id"], frequency_cm1=float(freqs[k]), x=m["vec"].tolist()) for k, m in enumerate(modes)])
        (mdir / f"cluster_vectors_{tag}.json").write_text(json.dumps(allm))
        chosen = [k for k, m in enumerate(modes) if m["id"] in sel]
        full = dict(
            salt_id=salt, structure_id=structure_id, sampling=sampling, coupling_set=cset, q_grid=grid,
            structure=dict(symbols=symbols, masses_amu=masses.tolist(), cell_angstrom=cell.tolist(), frac_positions=frac.tolist(),
                           cart_positions_angstrom=(frac @ cell).tolist(), molecule_id=lab.tolist(), is_anion_atom=anion.tolist(),
                           same_as_deposited=f"{salt}.extxyz (identical atom order and Cartesian frame)"),
            eigenvector_convention=(
                "e = eigenvector of the lattice-phase dynamical matrix D^L(q) = P D_phonopy(q) P^dagger, P = diag(exp(2 pi i q.frac_k)), "
                "mass-weighted, unit norm over the unit cell; rows = cell atoms (0-based, deposited order), columns x,y,z (Cartesian, cell frame). "
                "Supercell n1 x n2 x n3 (= q_grid), cell index n (integer vector): displacement of atom k in cell n per unit normal coordinate Q "
                "(amu^1/2 A): part 're': Re(e_k)/sqrt(N m_k) [q with 2q = G, e real]; part 'cos': sqrt(2/N) Re(e_k exp(2 pi i q.n))/sqrt(m_k); "
                "part 'sin': sqrt(2/N) Im(e_k exp(2 pi i q.n))/sqrt(m_k); N = n1 n2 n3, q = q_index / q_grid. cos/sin are the two degenerate "
                "standing waves of +/-q; their split depends on the phase origin, their sum of contributions does not."),
            modes=[dict(mode_id=modes[k]["id"], frequency_cm1=float(freqs[k]), q_index=list(modes[k]["q"]), band_index_0based=int(modes[k]["band"]),
                        part=modes[k]["part"], selection_reason=sorted(sel[modes[k]["id"]]), eig_re=modes[k]["eig"].real.reshape(-1, 3).tolist(),
                        eig_im=None if modes[k]["real_q"] else modes[k]["eig"].imag.reshape(-1, 3).tolist()) for k in chosen])
        (mdir / f"selected_modes_{tag}.json").write_text(json.dumps(full))
        # cluster XYZ animations for the selected modes
        adir = mdir / f"anim_cluster_{tag}"
        adir.mkdir(exist_ok=True)
        el, cpos, cm = man["symbols"], np.array(man["positions_angstrom"]), np.array(man["masses_amu"])
        for k in chosen:
            u = modes[k]["vec"].reshape(-1, 3) / np.sqrt(cm)[:, None]
            amp = VIS_MAX_DISP / np.abs(np.linalg.norm(u, axis=1)).max()
            fn = adir / (modes[k]["id"].replace(":", "_") + ".xyz")
            with open(fn, "w") as fh:
                for fr in range(N_FRAMES):
                    ph_ = math.sin(2 * math.pi * fr / N_FRAMES)
                    fh.write(f"{len(el)}\n{modes[k]['id']} {float(freqs[k]):.4f} cm-1 frame {fr}/{N_FRAMES} Q={ph_ * amp:.6f} amu^1/2 A "
                             f"(Q_vis={amp:.6f}, max atom displacement {VIS_MAX_DISP} A; metal frame; 300K rms Q={math.sqrt(mode_mean_square_q(float(freqs[k]), TEMP)):.6f})\n")
                    for s_, p_ in zip(el, cpos + ph_ * amp * u):
                        fh.write(f"{s_} {p_[0]:.6f} {p_[1]:.6f} {p_[2]:.6f}\n")


def family_for(salt):
    """Variant Gamma bands the validator matched to the parent family 154-157 (receipt details.family.variant.modes)."""
    import glob
    rec = glob.glob(str(RELEASE / "inputs" / salt / "reported" / "validator_receipt_*.json"))
    if not rec:
        return []
    fam = load_json(rec[0]).get("details", {}).get("family") or {}
    return (fam.get("variant") or {}).get("modes", []) if salt != "SEED" else FAMILY_PARENT


if __name__ == "__main__":
    dep = {}
    p = OUT / "manifest" / "deposit_index.json"
    if p.exists():
        for r in load_json(p):
            for rp in filter(None, r["recompute_release_paths"].split(";")):
                dep[rp] = dict(borealis_file_id=r["file_id"], borealis_filename=r["borealis_filename"], md5=r["md5"])
    for s in SALTS:
        run_salt(s, dep)
