"""Seed Gamma_II T1 vs phonon sampling (coordinator 2026-11-15).

The seed's couplings (51 mass-weighted directions on the anion, metal frame) are reused; only the phonons change.
A sampling grid n1 x n2 x n3 = the Gamma modes of that supercell, built from the commensurate q points of a phonopy set:
q with 2q = G gives real modes of the lattice-phase dynamical matrix; any other q (one of each +/-q) gives two standing
waves sqrt(2) Re / Im of the Bloch wave. Each mode is normalised over the whole supercell (1/sqrt(N cells)).
Evaluated on the carved anion (unwrapped positions), cluster translations projected out, rotated into the metal frame,
then projected on the directions exactly as export_excited_state_displacements / couplings_from_points do.

    python t1_sampling.py PHONOPY_YAML n1 n2 n3 [label]
"""
import itertools
import os
import json
import sys
from pathlib import Path

import numpy as np
import phonopy

sys.path.insert(0, "/h/327/igustin/ElAgente")
from Hypothesis_generation.skill_library.periodic_dft.excited_state_raman import coupling_operators, gamma2_powder  # noqa: E402
from Hypothesis_generation.skill_library.periodic_dft.low_mode_hessian import translations  # noqa: E402

G2 = Path("/project/igustin/QECT/t1loop_VOdmit2/gamma2/VOdmit2_ewald")
THZ_TO_CM1 = 33.35640951981521
SIGMAS, FIELD, TEMPS, CUT = (2.0, 3.0, 5.0, 7.0, 10.0, 15.0, 20.0, 30.0), 0.345, [300.0], 500.0
ROOT = Path("/project/igustin/QECT/t1loop_VOdmit2")


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"]]
    # unwrapped cluster positions (cell frame) and their lattice offsets from the cell atoms
    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, imag, bands = 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)
        if real_q:
            assert np.abs(dl.imag).max() < 1e-6 * np.abs(dl).max()
        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 not in acoustic and f[m] < -5:
                imag.extend([float(f[m])] * (1 if real_q else 2))
            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)
                bands.append(m)
    vecs = np.array(vecs)
    vecs = vecs - (vecs @ t) @ t.T
    vecs = (vecs.reshape(len(vecs), -1, 3) @ rot.T).reshape(len(vecs), -1)
    imag = np.array(imag)
    return np.array(freqs), vecs, int(np.prod(grid)), imag, np.array(bands)


def mode_fwhm(fit, freqs, bands, how, ph, man):
    """FWHM of every sampled mode: 'band' = the fitted Gamma mode of the same band index (own salt); 'freq' = median of the
    fitted widths within +/- 25 cm-1 (another salt's widths). Unfitted -> anion-weighted median of the fitted widths."""
    rows = fit["modes"]
    ok = [r for r in rows if r.get("fwhm") is not None]
    ph.run_qpoints([[0, 0, 0]], with_eigenvectors=True)
    e = ph.qpoints.eigenvectors[0]
    crow = np.ravel([[3 * a["cell_atom"], 3 * a["cell_atom"] + 1, 3 * a["cell_atom"] + 2] for a in man["atoms"]])
    if how == "band":
        w = np.array([(np.abs(e[crow, r["band"]]) ** 2).sum() for r in ok])
        f = np.array([r["fwhm"] for r in ok])
        order = np.argsort(f)
        med = float(f[order][np.searchsorted(np.cumsum(w[order]), w.sum() / 2)])
        table = {r["band"]: r["fwhm"] for r in ok}
        return np.array([table.get(int(b), med) for b in bands])
    nu, f = np.array([r["nu_dft"] for r in ok]), np.array([r["fwhm"] for r in ok])
    return np.array([np.median(f[np.abs(nu - x) <= 25]) if (np.abs(nu - x) <= 25).any() else np.median(f) for x in freqs])


def main():
    yaml, grid_arg = sys.argv[1], sys.argv[2:5]
    label = sys.argv[5] if len(sys.argv) > 5 else f"{Path(yaml).parent.name}_{'x'.join(grid_arg)}"
    cpath = Path(os.environ.get("COUPLINGS", G2 / "sweep" / "excited_state_couplings.json"))  # any variant's sweep
    cpl = json.loads(cpath.read_text())
    man = json.loads((ROOT / cpl["displacement_manifest"]).read_text())
    yaml = str(ROOT / man["phonon_dir"] / "phonopy_params.yaml") if yaml == "own" else yaml
    ph = phonopy.load(yaml)
    if grid_arg[0] == "auto":  # every equivalent-supercell width >= float(grid_arg[1]) A
        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)
        grid = np.array([max(1, int(np.ceil(float(grid_arg[1]) / w))) for w in widths])
        label = f"{label}_{'x'.join(map(str, grid))}"
    else:
        grid = np.array([int(x) for x in grid_arg])
    freqs, vecs, nq, imag, bands = cluster_modes(ph, man, grid)
    dirs = np.array(man["directions_mass_weighted"])
    c = vecs @ dirs.T
    coverage = (c**2).sum(axis=1) / np.maximum((vecs**2).sum(axis=1), 1e-300)
    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"]))
    d = int(cpl["d_count"])
    v0, h0 = (np.array(cpl["reference"][k]) for k in ("V_nevpt2", "h_soc"))
    ops = coupling_operators(dv, dh, d)
    t1 = {f"{s:g}": float(1 / gamma2_powder(v0, h0, ops, freqs, FIELD, TEMPS, s, d)["rate"][0]) for s in SIGMAS}
    widths = {}
    if os.environ.get("WIDTHS"):  # PREREGISTRATION.md amendment 1: per-pair sigma_ab = (Gamma_a + Gamma_b) / 2.355
        fwhm = mode_fwhm(json.loads(Path(os.environ["WIDTHS"]).read_text()), freqs, bands, os.environ.get("WIDTH_MAP", "band"), ph, man)
        sig = (fwhm[:, None] + fwhm[None, :]) / 2.355
        widths = {"widths": os.environ["WIDTHS"], "map": os.environ.get("WIDTH_MAP", "band"),
                  "fwhm_median": round(float(np.median(fwhm)), 3), "T1_perpair_gauss_us": round(1e6 / gamma2_powder(v0, h0, ops, freqs, FIELD, TEMPS, sig, d)["rate"][0], 4)}
        import Hypothesis_generation.skill_library.periodic_dft.excited_state_raman as esr
        gauss = esr._gauss
        esr._gauss = lambda x, s: (1.1774 * s / np.pi) / (x**2 + (1.1774 * s) ** 2)  # Lorentzian, same FWHM 2.355 s (sensitivity)
        try:
            widths["T1_perpair_lorentz_us"] = round(1e6 / gamma2_powder(v0, h0, ops, freqs, FIELD, TEMPS, sig, d)["rate"][0], 4)
        finally:
            esr._gauss = gauss
    weight = (vecs**2).sum(axis=1)
    out = {"label": label, "couplings": str(cpath), "phonopy": yaml, "grid": grid.tolist(), "n_q": nq, "n_modes": len(freqs),
           "anion_weight_total": round(float(weight.sum()), 3), "coverage_weighted": round(float((coverage * weight).sum() / weight.sum()), 4),
           "min_freq_cm1": round(float(freqs.min()), 2),
           "n_imaginary_below_minus5": len(imag), "most_imaginary_cm1": round(float(imag.min()), 1) if len(imag) else None, "T1_300K_us": {k: round(v * 1e6, 4) for k, v in t1.items()},
           "ratio_s20_over_s5": round(t1["20"] / t1["5"], 4), **widths}
    print(json.dumps(out))
    with open(Path(__file__).parent / "results.jsonl", "a") as fh:
        fh.write(json.dumps(out) + "\n")
    if (grid == 1).all():  # same-sampling check against the campaign's mode couplings
        np.save(Path(__file__).parent / f"{label}_freqs.npy", freqs)


if __name__ == "__main__":
    main()
