"""Recompute room-temperature Gamma_II spin-lattice T1 from the packaged inputs (no El Agente installation needed).

Two modes, both at 300 K, 0.345 T, powder average over the 14-point Lebedev grid (T1 = 1 / orientation-averaged rate):

  gamma  T1 from the mode couplings stored in a couplings file (the Gamma modes of the cell used by the campaign).
         This is what `compute_excited_state_spin_relaxation` and the validator `judge_t1_loop` compute.
             python t1_recompute.py gamma inputs/<salt>/couplings_judged.json --sigmas 5 10 20

  dense  T1 with the salt's own DFT force constants evaluated on a q-grid whose equivalent supercell is at least
         --min-width A wide in every direction (default 21 A, the paper's dense sampling). Needs phonopy.
         The direction couplings are projected on those modes exactly as the campaign tools do.
             python t1_recompute.py dense inputs/<salt>/couplings_dense.json inputs/<salt>/displacement_manifest_dense.json \
                 inputs/<salt>/phonopy_params.yaml --sigmas 3 5 7

`cluster_modes` and the projection below are the campaign's analysis script t1_sampling.py (copy in
code/source_at_commit_91594fcc/t1_sampling_campaign_analysis_script.py) with its imaginary-mode tally and band
bookkeeping removed; the physics functions come from t1_gamma2_core.py.
"""
import argparse
import itertools
import json
import sys
from pathlib import Path

import numpy as np

sys.path.insert(0, str(Path(__file__).resolve().parent))
from t1_gamma2_core import coupling_operators, gamma2_powder, translations  # noqa: E402

THZ_TO_CM1 = 33.35640951981521
FIELD, TEMPS, CUT = 0.345, [300.0], 500.0


def t1_gamma(couplings: dict, sigmas) -> dict:
    """T1 (us) from the stored Gamma-mode couplings (as compute_excited_state_spin_relaxation / judge_t1_loop)."""
    d = int(couplings["d_count"])
    v0, h0 = (np.array(couplings["reference"][k], dtype=float) for k in ("V_nevpt2", "h_soc"))
    freqs = np.array(couplings["modes"]["frequencies_cm1"], dtype=float)
    dv = np.array(couplings["mode_couplings"]["dV"], dtype=float); dh = np.array(couplings["mode_couplings"]["dh"], dtype=float)
    ops = coupling_operators(dv, dh, d)
    return {f"{s:g}": 1e6 / float(gamma2_powder(v0, h0, ops, freqs, FIELD, TEMPS, float(s), d)["rate"][0]) for s in sigmas}


def cluster_modes(ph, man, grid):
    """(freqs cm-1, mass-weighted cluster vectors in the metal frame, translations removed) of the grid's supercell Gamma modes."""
    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, f"cluster atoms are not images of their cell atoms: {np.abs(off - off.round()).max()}"
    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, freqs, vecs = 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, :]  # lattice-phase convention
        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 * 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)):
            if m in acoustic or f[m] <= 0 or f[m] > CUT:
                continue  # Gamma acoustic, imaginary, above the cutoff
            e = v[rows, m] * lat / np.sqrt(ncell)
            for part in ([e.real] if real_q else [np.sqrt(2) * e.real, np.sqrt(2) * e.imag]):
                freqs.append(f[m])
                vecs.append(part)
    vecs = np.array(vecs)
    vecs = vecs - (vecs @ t) @ t.T
    vecs = (vecs.reshape(len(vecs), -1, 3) @ rot.T).reshape(len(vecs), -1)
    return np.array(freqs), vecs


def dense_grid(ph, min_width: float):
    cell = ph.primitive.cell
    widths = abs(np.linalg.det(cell)) / np.linalg.norm(np.cross(cell[[1, 2, 0]], cell[[2, 0, 1]]), axis=1)
    return np.array([max(1, int(np.ceil(min_width / w))) for w in widths])


def t1_dense(couplings: dict, manifest: dict, phonopy_yaml: str, sigmas, min_width: float = 21.0, grid=None) -> dict:
    import phonopy

    ph = phonopy.load(phonopy_yaml)
    grid = np.array(grid) if grid is not None else dense_grid(ph, min_width)
    freqs, vecs = cluster_modes(ph, manifest, grid)
    c = vecs @ np.array(manifest["directions_mass_weighted"]).T
    dv = np.einsum("aj,jmn->amn", c, np.array(couplings["direction_couplings"]["dV"]))
    dh = np.einsum("aj,jkmn->akmn", c, np.array(couplings["direction_couplings"]["dh"]))
    d = int(couplings["d_count"])
    v0, h0 = (np.array(couplings["reference"][k]) for k in ("V_nevpt2", "h_soc"))
    ops = coupling_operators(dv, dh, d)
    t1 = {f"{s:g}": 1e6 / float(gamma2_powder(v0, h0, ops, freqs, FIELD, TEMPS, float(s), d)["rate"][0]) for s in sigmas}
    return {"grid": grid.tolist(), "n_modes": len(freqs), "T1_us": t1}


def main():
    p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    p.add_argument("mode", choices=["gamma", "dense"])
    p.add_argument("couplings")
    p.add_argument("manifest", nargs="?")
    p.add_argument("phonopy_yaml", nargs="?")
    p.add_argument("--sigmas", nargs="+", type=float, default=[5, 10, 20])
    p.add_argument("--min-width", type=float, default=21.0)
    a = p.parse_args()
    cpl = json.loads(Path(a.couplings).read_text())
    if a.mode == "gamma":
        out = {"mode": "gamma", "T1_us": t1_gamma(cpl, a.sigmas)}
    else:
        man = json.loads(Path(a.manifest).read_text())
        out = {"mode": "dense", **t1_dense(cpl, man, a.phonopy_yaml, a.sigmas, a.min_width)}
    print(json.dumps(out, indent=1))


if __name__ == "__main__":
    main()
