"""Excited-state two-phonon spin-lattice relaxation (Gamma_II) of an S = 1/2 d1 or d9 ion.

Mariano, Lunghi et al. 2024 (Gamma_II of the fourth-order rate, their Eqs. 5-6); its field-independent part is the non-Abelian
Berry-curvature mechanism of Shushkov 2024. The spin-Hamiltonian route (Gamma_I, spin_relaxation.compute_spin_relaxation_time)
sees the d-d excited states only through g and A; here they are the explicit intermediate states of a two-phonon process that
is second order in the vibronic coupling. On VOPc it is ~1e4x faster than Gamma_I's Raman rate at 100-300 K. With consistent
NEVPT2 levels and couplings T1 = 14 / 0.84 us at 100 / 300 K (measured 20 / 1.1 us); with the excited levels / dx2-y2
covalency moved to reproduce the measured g_par and g_perp, and sigma 5-20 cm-1, 8.5-17 us / 0.49-1.15 us
(QECT/_tool_validation/gammaII/followup). Gamma-only phonons: T1 1.7-3.4x too long at 40 K.

Chain:
  export_excited_state_displacements(cluster_manifest, phonon_dir, oxidation_state) writes orca/start_orbitals.inp (ROHF),
    orca/reference.inp (CASSCF(n,5)/SC-NEVPT2 + ab initio SOC, AILFT; AVAS(Valence-D) on the ROHF orbitals) and
    orca/sweep_template.inp (the same CASSCF without NEVPT2), plus +/-Q members along orthonormal molecular directions that
    span the crystal's Gamma modes up to 500 cm-1 -> run start_orbitals.inp, then reference.inp (same folder)
  -> prepare_orca_displacement_sweep(sweep_template.inp, manifest, reference_gbw=orca/reference.gbw) (refuses an unusable
     reference) -> submit_orca_displacement_sweep -> collect_excited_state_couplings(sweep manifest)
  -> compute_excited_state_spin_relaxation(couplings, spin_relaxation_json=<compute_spin_relaxation_time output>).
Pre-screen without DFT phonons: phonon_dir = an MLIP (UMA) Gamma set of the same cell (its fc_provenance.json says 'MLIP: ...');
the manifest, couplings and T1 carry phonon_source and MLIP_PRESCREEN_NOTE. Isolated-molecule (gas-phase) normal modes are not a
usable pre-screen: at the crystal geometry T1(300 K) is 0.50x (VOPc) and 2.1x (VO(acac)2) the crystal value, so the two invert,
and a gas-phase relaxation moved VO(acac)2 to 0.07x (QECT/_tool_validation/gammaII/gasphase).

Model (cm-1). Real d basis [dz2, dxz, dyz, dx2-y2, dxy] (Cartesian 2z2-x2-y2, xz, yz, x2-y2, xy) x spin (up, down), index
2 orbital + spin; the one-electron operator
    h = V_LF (x) 1 + sum_k (i h_k) (x) s_k + mu_B B.(l + g_e s)
with V_LF the AILFT ligand-field matrix and h_k ORCA's ab initio SOC matrices 'AI-SOC-k' (RI-SOMF; real antisymmetric,
= zeta Im(l_k) for an ideal d shell). d1: the ion's states are those of h. d9 (one hole): <h_p|O|h_q> = tr(O) delta_pq - O_qp
for every one-body O, so H_ion = tr(h) 1 - h^T (the energy of the full shell minus the removed electron's) and every coupling
transforms the same way; lambda = -zeta and the g > 2 shifts then follow by themselves.

Quasi-diabatic basis. AILFT expresses V_LF and h_k on the active orbitals ('actorbs dorbs'); their metal-d parts S (d functions
x active orbitals, summed over the printed shells) define the re-aligned basis chi = phi T, T = S^T (S S^T)^-1/2 (symmetric
Loewdin orthonormalisation onto the ideal d functions): V -> T^T V T, h_k -> T^T h_k T. VOPc, 3 deg rigid rotation: the native
AILFT basis misses the rotated V by 75 cm-1 (of a 1194 cm-1 change), the re-aligned one by 0.1 cm-1. In that basis dH/dq by
central differences IS the vibronic coupling, with no NAC phase problem; the FD libration coupling must equal -i[J, H].

Geometry. The molecule is put in a metal frame (z = the donors' most distinct second-moment axis, snapped onto the axial
bond(s) -- V=O -- or the square-plane normal; x = the in-plane donor directions averaged four-fold, so dx2-y2 points at the
donors). Directions: the
molecule-restricted, translation-free, mass-weighted Gamma vectors of the modes <= soft_cutoff_cm1 are spanned exactly
(SVD, s >= 1e-3 s_max); those up to mode_cutoff_cm1 add the directions holding extension_weight of their weight outside that
span. Steps: the metal + donor atoms move 0.01 A rms, no atom more than 0.05 A; the first directions also get +/-2Q.
dH/dQ_alpha = sum_j (v_alpha . u_j) dH/dq_j (v_alpha the restricted vector, u_j the directions).

Level of theory. The levels are NEVPT2. The couplings are NEVPT2 too: by default every member runs SC-NEVPT2 (member_level
'nevpt2'); with member_level 'casscf' the reference's NEVPT2 - CASSCF orbital shifts are carried on each member's CASSCF LF
eigenvectors (nevpt2_constant_shift: ORCA's NEVPT2 AILFT keeps the CASSCF eigenvectors, so the ground-excited couplings agree to
0.01-0.1% on VOPc and T1 to 1%). CASSCF couplings with NEVPT2 levels (the prototype's mixed scheme) are 21-23% too small for the
ground-excited elements and made T1 1.8x too long; that number is still reported (T1_II_mixed_scheme_s).

Covalency (Cu(II)). The CAS(9,5) hole is too metal-localised (CuOEP: 91.6% Cu dx2-y2 Loewdin vs ~66-70% from the measured A and
g-bracketing DFT), so its SOC is too large: NEVPT2 g-shifts 1.6-1.8x the measured ones while the NEVPT2 d-d energies are right (CuCl4^2-:
within 0.5k cm-1 of experiment, g-shift 2.1x). compute_excited_state_spin_relaxation(covalency_g_target=...) applies the ligand-field cure:
anisotropic orbital reduction factors k_par (z) / k_perp (x, y) on EVERY SOC matrix element (h_k and dh_k/dQ), fitted by
fit_orbital_reduction so the model g (SOC and orbital Zeeman both reduced; the orbital Zeeman first calibrated on the reference's own
ORCA g) equals the target (CuOEP measured g: k_par 0.740, k_perp 0.769; Gamma_II x0.58, T1 x1.7). CAS(11,6) with the N-sigma(b1g) orbital is
NOT a usable reference: its sigma -> d LMCT root is an intruder for NEVPT2 / QD-NEVPT2 / DCD-CAS(2) (QECT/_tool_validation/gammaII/cu_covalency).

Rate (Mariano 2024 Eqs. 5-6) for b -> a (the Zeeman-split ground Kramers doublet), phonon alpha absorbed and beta emitted:
    T_ab = sum_c V^alpha_ac V^beta_cb / (E_c - E_b + w_beta) + V^beta_ac V^alpha_cb / (E_c - E_b - w_alpha)
    W_b->a = 4 pi^2 c sum_{alpha != beta} |T_ab|^2 <Q_alpha^2>_0 <Q_beta^2>_0 D(w_ab - w_alpha + w_beta) n(w_alpha') (n(w_beta') + 1)
V^alpha = <|dH_ion/dQ_alpha|> in the eigenbasis of H_ion(B) (cm-1 per amu^1/2 A); c runs over the 8 excited states. This is
the golden-rule prefactor of the Gamma_I engine (2 pi^2 c over ordered pairs and both sign pairs = 4 pi^2 c per process), its
Gaussian D (sigma = standard deviation), its energy-conserving Bose factors (w' = w -+ d/2: detailed balance exact) and its
exclusions (the same mode absorbed and emitted; double absorption / emission). T1 = 1/(W_up + W_down) per field direction
(the recovery area of a two-level system), 1/T1 averaged over Lebedev-14. To first order in w the amplitude is
-w [V^alpha, V^beta]_ab / dE^2 (the curvature term: B-independent, rate ~ zeta^2 and ~ dE^-4 at fixed couplings and mixing);
the w-independent anticommutator vanishes
for a Kramers doublet as B -> 0 (Van Vleck). Total = 1/(1/T1_I + 1/T1_II) with T1_I the Gamma_I Raman T1 of
compute_spin_relaxation_time at the same field, sigma and temperatures.
"""

from __future__ import annotations

import hashlib
import json
import math
import re
from pathlib import Path
from typing import Annotated, Any, Dict

import numpy as np
from langchain.tools import ToolRuntime
from langchain_core.tools import tool

from Hypothesis_generation.skill_library.periodic_dft import crystal_phonons as cp
from Hypothesis_generation.skill_library.periodic_dft import harness as _h
from Hypothesis_generation.skill_library.periodic_dft import spin_relaxation as sr
from Hypothesis_generation.skill_library.periodic_dft.low_mode_hessian import translations

KIND = "excited_state_fd"
COUPLINGS_KIND = "excited_state_couplings"
MANIFEST_NAME = "excited_state_displacements_manifest.json"
D_LABELS = ("dz2", "dxz", "dyz", "dx2-y2", "dxy")
EH_TO_CM1 = 219474.6313705
G_E = 2.00231930436
MU_B = sr.MU_B_CM1_PER_T
PRE = 4 * math.pi**2 * cp.C_CM_PER_S
SOFT_RCOND = 1e-3
#: S = 1/2 one-electron / one-hole ions the 10-state model describes; 5 doublet roots each.
SUPPORTED_D_COUNTS = (1, 9)
MEMBER_LEVELS = ("nevpt2", "casscf")
#: Gamma_II on MLIP (UMA) Gamma phonons instead of DFT ones, same couplings (QECT/_tool_validation/gammaII/gasphase, 2026-10-08).
MLIP_PRESCREEN_NOTE = ("MLIP Gamma phonons: a pre-screen, not a T1 prediction. VOPc and VO(acac)2, UMA uma-s-1p2 Gamma modes on the DFT-relaxed "
                       "cell (Hessian at the DFT geometry): T1 = 0.80x / 0.79x the DFT-phonon Gamma_II at 300 K, 0.99x / 1.03x at 100 K, "
                       "3.4x / 1.7x at 40 K; with the ions relaxed to the UMA minimum 1.08x / 0.53x at 300 K. Rank only candidates whose "
                       "T1(100-300 K) differ by > 2x and confirm the leaders with DFT phonons. (Gas-phase normal modes fail: 0.50x / 0.07x at "
                       "300 K after a gas-phase relaxation, 0.50x / 2.1x at the crystal geometry.)")
MEMBER_LEVEL_DOC = ("Sweep members' AILFT level. 'nevpt2' (default): NEVPT2 AILFT matrices at every member, couplings consistent with the "
                    "NEVPT2 levels (VOPc: ~3.6 core-h per member at 8 cores). 'casscf': ~2.7x cheaper CASSCF members (VOPc, 8 cores: 10.6 vs 28.8 min); the reference's NEVPT2 level "
                    "shifts are carried on each member's CASSCF LF eigenvectors (VOPc: Gamma_II couplings within 0.1%, T1 within 1% of 'nevpt2'). "
                    "Never CASSCF couplings with NEVPT2 levels (the 'mixed' scheme): its ground-excited couplings are 21-23% low, T1 1.8x long.")



# --------------------------------------------------------------------------- #
# d-shell operators and the ion Hamiltonian
# --------------------------------------------------------------------------- #


def l_matrices() -> np.ndarray:
    """(3, 5, 5) l_x, l_y, l_z in the real d basis (Condon-Shortley, '+' Cartesian phases; purely imaginary)."""
    m = np.arange(-2, 3)
    lz = np.diag(m).astype(complex)
    lp = np.zeros((5, 5), complex)
    for k, mm in enumerate(m[:-1]):
        lp[k + 1, k] = math.sqrt(6 - mm * (mm + 1))
    lx, ly = (lp + lp.conj().T) / 2, (lp - lp.conj().T) / 2j
    s = 1 / math.sqrt(2)
    c = np.zeros((5, 5), complex)  # columns: the real orbitals in the |2, m> basis
    c[2, 0] = 1
    c[1, 1], c[3, 1] = s, -s
    c[1, 2], c[3, 2] = 1j * s, 1j * s
    c[4, 3], c[0, 3] = s, s
    c[4, 4], c[0, 4] = -1j * s, 1j * s
    return np.array([c.conj().T @ op @ c for op in (lx, ly, lz)])


L_ORB = l_matrices()
S_SPIN = np.array([[[0, 1], [1, 0]], [[0, -1j], [1j, 0]], [[1, 0], [0, -1]]], dtype=complex) / 2
L_FULL = np.array([np.kron(L_ORB[k], np.eye(2)) for k in range(3)])
S_FULL = np.array([np.kron(np.eye(5), S_SPIN[k]) for k in range(3)])
J_FULL = L_FULL + S_FULL


def zeta_soc(zeta: float) -> np.ndarray:
    """h_k of an ideal d shell with spin-orbit constant zeta: zeta Im(l_k)."""
    return zeta * np.array([L_ORB[k].imag for k in range(3)])


def one_electron(v, h, bvec=(0.0, 0.0, 0.0)) -> np.ndarray:
    """10 x 10 one-electron operator V (x) 1 + sum_k (i h_k) (x) s_k + mu_B B.(l + g_e s) (cm-1)."""
    out = np.kron(np.asarray(v, dtype=float), np.eye(2)).astype(complex)
    out += sum(np.kron(1j * np.asarray(h[k], dtype=float), S_SPIN[k]) for k in range(3))
    return out + MU_B * np.einsum("k,kij->ij", np.asarray(bvec, dtype=float), L_FULL + G_E * S_FULL)


def ion(op, d_count: int) -> np.ndarray:
    """The d^n ion's matrix of a one-body d-shell operator: itself for d1; tr(O) 1 - O^T for d9 (one hole)."""
    op = np.asarray(op)
    if d_count == 1:
        return op
    if d_count == 9:
        return np.trace(op) * np.eye(op.shape[-1]) - op.T
    raise ValueError(f"d{d_count}: the Gamma_II model is a one-electron (d1) or one-hole (d9) S = 1/2 ion.")


def ion_hamiltonian(v, h, bvec, d_count: int) -> np.ndarray:
    out = ion(one_electron(v, h, bvec), d_count)
    return (out + out.conj().T) / 2


def coupling_operators(dv, dh, d_count: int) -> np.ndarray:
    """(N, 10, 10) dH_ion/dQ per mode from dV/dQ (N, 5, 5) and dh_k/dQ (N, 3, 5, 5)."""
    return np.array([ion(one_electron(a, b), d_count) for a, b in zip(dv, dh)]).reshape(-1, 10, 10)


def g_tensor(v, h, d_count: int, l_scale=(1.0, 1.0, 1.0)) -> tuple[np.ndarray, np.ndarray]:
    """Principal g values (ascending) and axes (columns) of the ground Kramers doublet: g g^T = 2 tr(M_i M_j),
    M_i = P (k_i l_i + g_e s_i) P in the ion picture (k_i = l_scale: orbital reduction of the orbital Zeeman term)."""
    _e, u = np.linalg.eigh(ion_hamiltonian(v, h, (0.0, 0.0, 0.0), d_count))
    p = u[:, :2]
    m = np.array([p.conj().T @ ion(float(l_scale[k]) * L_FULL[k] + G_E * S_FULL[k], d_count) @ p for k in range(3)])
    w, axes = np.linalg.eigh(2 * np.real(np.einsum("iab,jba->ij", m, m)))
    return np.sqrt(np.clip(w, 0.0, None)), axes


def axial_g(g, axes) -> tuple[float, float]:
    """(g_par, g_perp): the principal value along the frame z (metal axis) and the mean of the other two."""
    par = int(np.argmax(np.abs(np.asarray(axes)[2])))
    return float(g[par]), float(np.mean(np.delete(np.asarray(g), par)))


def principal_to_axial(g) -> tuple[float, float]:
    """(g_par, g_perp) from three principal values without axes: the unique one (farthest from the median) is g_par."""
    g = np.asarray(g, dtype=float)
    par = int(np.argmax(np.abs(g - np.median(g))))
    return float(g[par]), float(np.mean(np.delete(g, par)))


# --------------------------------------------------------------------------- #
# Covalency (orbital reduction) correction of the d-shell SOC
# --------------------------------------------------------------------------- #

#: CuOEP in ZnOEP (1:100), 77 K X-band CW EPR, EasySpin fit (Kazmierczak et al., Chem. Sci. 2024, ESI Table S3).
CUOEP_EXPERIMENT_G = (2.195, 2.047)
COVALENCY_DOC = (
    "Covalency (orbital-reduction) correction of the d-shell SOC, from a target g. '' = none (default; d1 vanadyl needs none). For Cu(II) "
    "pass the path of a B3LYP ZORA EPR output of the same molecule (its g(tot) is used; the GENERAL rule, identical for candidates and "
    "controls; CuOEP: shifts 0.88-0.91x the measured ones; NOT B3LYP-38%HF, 1.2x; NOT a CAS(11,6) output, whose NEVPT2 has an LMCT intruder). "
    "A measured 'g_par g_perp' (CuOEP 2.195 2.047) is for sensitivity checks only: fitting a control to its own EPR breaks the blind test. The CAS(9,5) hole is too "
    "ionic (CuOEP: g-shifts 1.6-1.8x the measured ones; CuCl4^2- d-d energies right), so every SOC matrix element h_k and dh_k/dQ is scaled by "
    "k_perp (x, y) or k_par (z), the anisotropic LFT orbital reduction factors, fitted so the model g (SOC and orbital Zeeman both reduced, the "
    "orbital Zeeman first calibrated on the reference's own ORCA g) equals the target. Gamma_II then drops ~k^2 (CuOEP x0.58).")


def soc_reduced(h, kappa) -> np.ndarray:
    """SOC matrices with Cartesian component k scaled by kappa[k]: h (3, 5, 5) or dh (N, 3, 5, 5)."""
    h = np.asarray(h, dtype=float)
    return h * np.asarray(kappa, dtype=float).reshape((1,) * (h.ndim - 3) + (3, 1, 1))


def fit_orbital_reduction(v, h, d_count: int, g_target, g_reference=None) -> Dict[str, Any]:
    """Anisotropic orbital reduction (k_par, k_perp) of the d shell that makes the model g equal g_target = (g_par, g_perp).

    Ligand-field practice (Owen; Abragam & Bleaney): covalency reduces the spin-orbit AND orbital Zeeman matrix elements of the d
    shell by the same factors, so a g-shift scales ~k^2 and the SOC-induced mixing that drives Gamma_II ~k. Step 1: the model's
    ideal-d orbital Zeeman is reduced by k_l so the model reproduces g_reference (ORCA's own QDPT g of the CAS reference, whose
    orbitals carry the CAS covalency that the ab initio SOC h already contains). Step 2: h and the orbital Zeeman are both scaled by
    kappa = (k_perp, k_perp, k_par) per Cartesian component (frame z = metal axis) until the model g equals g_target."""
    from scipy.optimize import least_squares

    target = np.asarray(g_target, dtype=float)

    def model(kap, kl):
        s, sl = np.array([kap[1], kap[1], kap[0]]), np.array([kl[1], kl[1], kl[0]])
        return np.array(axial_g(*g_tensor(v, soc_reduced(h, s), d_count, s * sl)))

    def solve(fun, goal):
        res = least_squares(lambda x: (fun(x) - goal) / np.maximum(np.abs(goal - G_E), 1e-4), [1.0, 1.0], bounds=(0.05, 3.0), xtol=1e-12, ftol=1e-12)
        return res.x, float(np.max(np.abs(fun(res.x) - goal)))

    k_l, ref_resid = np.ones(2), None
    if g_reference is not None:
        ref = np.asarray(g_reference, dtype=float)
        ref = np.array(principal_to_axial(ref)) if ref.size == 3 else ref
        k_l, ref_resid = solve(lambda x: model((1.0, 1.0), x), ref)
    kap, resid = solve(lambda x: model(x, k_l), target)
    before = model((1.0, 1.0), k_l)
    return {"k_par": float(kap[0]), "k_perp": float(kap[1]), "kappa_xyz": [float(kap[1]), float(kap[1]), float(kap[0])],
            "k_l_par": float(k_l[0]), "k_l_perp": float(k_l[1]), "g_target": target.round(6).tolist(),
            "g_model_uncorrected": before.round(6).tolist(), "g_model_corrected": model(kap, k_l).round(6).tolist(),
            "max_abs_g_residual": resid, "reference_g_residual": ref_resid,
            "shift_ratio_target_over_uncorrected": ((target - G_E) / (before - G_E)).round(4).tolist()}


def target_g(spec: str, root=None) -> tuple[tuple[float, float], str]:
    """(g_par, g_perp) from 'g_par g_perp' (or three principal values) or from an ORCA output: the last QD-NEVPT2 QDPT g, else the last
    DCD-CAS(2) 'Total g-values', else the NEVPT2-QDPT g, else the last printed principal g values (DFT EPR / CASSCF QDPT)."""
    parts = spec.replace(",", " ").split()
    try:
        vals = [float(x) for x in parts]
    except ValueError:
        vals = None
    if vals is not None and len(vals) in (2, 3):
        if len(vals) == 2:
            return (vals[0], vals[1]), "explicit"
        return principal_to_axial(vals), "explicit principal values"
    path = _h._resolve_path(root, spec, must_exist=True, dir_ok=False) if root is not None else Path(spec)
    text = Path(path).read_text(errors="ignore")
    found, label = None, ""
    for title, lab in (("QDPT WITH QD-NEVPT2 ENERGIES", "QD-NEVPT2 QDPT"), ("QDPT WITH NEVPT2 DIAGONAL ENERGIES", "NEVPT2 QDPT")):
        k = text.rfind(title)
        m = re.search(r"g-factors:\s*\n\s*(-?[\d.]+)\s+(-?[\d.]+)\s+(-?[\d.]+)", text[k:]) if k >= 0 else None
        if m:
            found, label = [float(x) for x in m.groups()], lab
            break
    if found is None:
        m = list(re.finditer(r"Total g-values:\s+(-?[\d.]+)\s+(-?[\d.]+)\s+(-?[\d.]+)", text))
        if m:
            found, label = [float(x) for x in m[-1].groups()], "DCD-CAS(2)"
    if found is None:
        m = list(re.finditer(r"g-factors:\s*\n\s*(-?[\d.]+)\s+(-?[\d.]+)\s+(-?[\d.]+)", text)) or \
            list(re.finditer(r"g\(tot\)\s+(-?[\d.]+)\s+(-?[\d.]+)\s+(-?[\d.]+)", text))
        if m:
            found, label = [float(x) for x in m[-1].groups()], "last printed g"
    if found is None:
        raise ValueError(f"{Path(path).name}: no g values found (QDPT 'g-factors', DCD 'Total g-values' or EPR 'g(tot)')")
    return principal_to_axial(found), f"{label} of {Path(path).name}"


def orbital_character(u_states) -> np.ndarray:
    """(n_states, 5) d-orbital weights of ion eigenvectors (columns of u_states): the electron's (d1) or the hole's (d9)."""
    w = np.abs(np.asarray(u_states)) ** 2
    return (w[0::2] + w[1::2]).T


# --------------------------------------------------------------------------- #
# Gamma_II rates
# --------------------------------------------------------------------------- #


def _gauss(x, sigma: float):
    return np.exp(-0.5 * (x / sigma) ** 2) / (math.sqrt(2 * math.pi) * sigma)


def spin_flip_rates(energies, vm, freqs, temps, sigma: float, cset=None, part: str = "full") -> dict[str, np.ndarray]:
    """Per temperature and ordered mode pair (alpha absorbed, beta emitted): the rates (s^-1) 'down' (state 1 -> 0) and 'up'
    (0 -> 1) between the two lowest states through the intermediate states cset (default: every other state).
    vm (N, n, n) = <i|dH/dQ_alpha|j> in the eigenbasis of energies (cm-1). part 'full' = Mariano's amplitude; 'curvature' =
    its first order in w, -w_mean [V^alpha, V^beta] / dE^2 (Shushkov's term). Returns {'down', 'up'}: (n_T, N, N)."""
    e = np.asarray(energies, dtype=float)
    w = np.asarray(freqs, dtype=float)
    c = np.asarray(list(range(2, len(e))) if cset is None else list(cset))
    q2 = sr.zero_point_q2(w)
    fa, fb = np.repeat(w[:, None], len(w), axis=1), np.repeat(w[None, :], len(w), axis=0)
    off = ~np.eye(len(w), dtype=bool)  # absorbing and emitting the same mode leaves the bath unchanged: excluded (as Gamma_I)
    out: dict[str, np.ndarray] = {}
    for name, fin, ini in (("down", 0, 1), ("up", 1, 0)):
        d = (e[fin] - e[ini]) - (fa - fb)  # mismatch: w_alpha - w_beta must equal the spin's energy gain
        wa, wb = fa + d / 2, fb - d / 2  # energy-conserving phonon energies (detailed balance exact)
        ok = (wa > 0) & (wb > 0) & off
        wa, wb = np.where(ok, wa, 1.0), np.where(ok, wb, 1.0)
        va, vb = vm[:, fin][:, c], vm[:, :, ini][:, c]  # V^alpha_{fin c}, V^alpha_{c ini}
        de = e[c] - e[ini]
        if part == "full":
            amp = np.einsum("ac,bc,abc->ab", va, vb, 1.0 / (de[None, None, :] + wb[:, :, None])) \
                + np.einsum("bc,ac,abc->ab", va, vb, 1.0 / (de[None, None, :] - wa[:, :, None]))
        elif part == "curvature":
            amp = -(wa + wb) / 2 * (np.einsum("ac,bc,c->ab", va, vb, de**-2.0) - np.einsum("bc,ac,c->ab", va, vb, de**-2.0))
        else:
            raise ValueError("part must be 'full' or 'curvature'")
        strength = PRE * np.abs(amp) ** 2 * q2[:, None] * q2[None, :]
        out[name] = np.array([np.where(ok, strength * _gauss(d, sigma) * sr.bose(wa, t) * (sr.bose(wb, t) + 1), 0.0) for t in temps])
    return out


def gamma2_direction(v, h, dops, freqs, bvec, temps, sigma: float, d_count: int, cset=None, part: str = "full") -> dict[str, Any]:
    """Eigenstates of H_ion(B) and the per-pair down/up rates for one field vector (tesla)."""
    e, u = np.linalg.eigh(ion_hamiltonian(v, h, bvec, d_count))
    vm = np.einsum("ji,ajk,kl->ail", u.conj(), dops, u)
    rates = spin_flip_rates(e, vm, freqs, temps, sigma, cset, part)
    down, up = rates["down"].sum(axis=(1, 2)), rates["up"].sum(axis=(1, 2))
    boltz = np.exp(-sr.HC_OVER_K_CM_K * (e[1] - e[0]) / np.asarray(temps, dtype=float))
    balance = np.where(down > 0, np.abs(up / np.where(down > 0, down, 1.0) / boltz - 1.0), 0.0)
    return {"energies": e, "vectors": u, "rate": down + up, "pairs": rates["down"] + rates["up"], "balance": balance}


def gamma2_powder(v, h, dops, freqs, field_tesla: float, temps, sigma: float, d_count: int, directions=None, **kw) -> dict[str, Any]:
    """1/T1 = W_up + W_down averaged over field directions (default Lebedev-14) and the per-pair rates of that average."""
    dirs, wts = sr.lebedev14() if directions is None else directions
    rate, pairs, balance = np.zeros(len(temps)), np.zeros((len(temps), len(freqs), len(freqs))), 0.0
    for n, wt in zip(dirs, wts):
        out = gamma2_direction(v, h, dops, freqs, float(field_tesla) * np.asarray(n, dtype=float), temps, sigma, d_count, **kw)
        rate += wt * out["rate"]
        pairs += wt * out["pairs"]
        balance = max(balance, float(np.max(out["balance"])))
    return {"rate": rate, "pairs": pairs, "balance": balance}


# --------------------------------------------------------------------------- #
# ORCA CASSCF / NEVPT2 + AILFT outputs
# --------------------------------------------------------------------------- #


def _floats(line: str) -> list[float]:
    return [float(x) for x in re.findall(r"-?\d+\.\d*(?:[eE][-+]?\d+)?", line)]


def _soc_matrix(text: str, comp: str) -> np.ndarray:
    k = text.find(f"AI-SOC-{comp} integrals (cm-1)")
    if k < 0:
        raise ValueError(f"no 'AI-SOC-{comp} integrals' block (rel dosoc true missing?)")
    lines = text[k:].splitlines()[2:7]  # title, column header, 5 rows 'i  v v v v v'
    return np.array([_floats(" ".join(line.split()[1:]))[:5] for line in lines])


def _eigenfunctions(segment: str) -> tuple[np.ndarray, np.ndarray]:
    k = segment.find("The ligand field one electron eigenfunctions:")
    lines = segment[k:].splitlines()
    j = next(i for i, line in enumerate(lines) if line.strip().startswith("Orbital") and "Energy" in line)
    header = lines[j].replace("Energy (eV)", "").replace("Energy(cm-1)", "").split()[1:]
    if header != list(D_LABELS):
        raise ValueError(f"unexpected AILFT orbital order {header}")
    rows = [line.split() for line in lines[j + 1 : j + 6]]
    return np.array([float(r[2]) for r in rows]), np.array([[float(x) for x in r[3:8]] for r in rows])


def parse_ailft_output(path) -> dict[str, Any]:
    """Raw AILFT content of an ORCA 6 CASSCF(n,5) (+NEVPT2) output with 'actorbs dorbs' and SOC."""
    text = Path(path).read_text(errors="ignore")
    head = re.search(r"AB INITIO LIGAND FIELD THEORY\s*\n\s*d(\d+) configuration", text)
    if not head:
        raise ValueError("no AILFT block ('actorbs dorbs' with 5 active orbitals)")
    mos = re.search(r"MOs (\d+) to (\d+)", text[head.end() : head.end() + 400])
    phases = re.search(r"orbital phases =([^\n]*)", text)
    k = text.find("Metal/Atom d-orbital parts of active orbitals")
    if k < 0:
        raise ValueError("no 'Metal/Atom d-orbital parts of active orbitals' block")
    shells, current = {}, None
    for line in text[k:].splitlines()[1:]:
        t = line.split()
        if t and t[0] == "Shell":
            current = int(t[1])
            shells[current] = []
        elif t and current is not None and t[0].rstrip(":") in {"dz2", "dxz", "dyz", "dx2y2", "dxy"}:
            shells[current].append(_floats(line)[-5:])
        elif t and not all(x.isdigit() for x in t):
            break
    dparts = sum(np.array(rows) for rows in shells.values() if len(rows) == 5)
    sections = {}
    for m in re.finditer(r"AILFT MATRIX ELEMENTS \((\w+)\)", text):
        end = text.find("AILFT MATRIX ELEMENTS (", m.end())
        sections[m.group(1).upper()] = _eigenfunctions(text[m.start() : end if end > 0 else len(text)])
    k = text.rfind("CAS-SCF STATES FOR BLOCK")
    roots = np.array([float(x) for x in re.findall(r"ROOT\s+\d+:\s+E=\s+(-?[\d.]+)\s+Eh", text[k : k + 20000])][:5]) if k >= 0 else np.zeros(0)
    nev_roots = np.array([float(x) for x in re.findall(r"Total Energy \(E0\+dE\)\s*:\s*E\s*=\s*(-?[\d.]+)", text)][:5])
    k = text.find("SPIN ORBIT COUPLING (based on CASSCF orbitals)")
    soc = np.array([_soc_matrix(text[k:], comp) for comp in "XYZ"]) if k >= 0 else None
    g_nev = None
    k = text.find("QDPT WITH NEVPT2 DIAGONAL ENERGIES")
    if k >= 0:
        g = re.search(r"g-factors:\s*\n\s*(-?[\d.]+)\s+(-?[\d.]+)\s+(-?[\d.]+)", text[k:])
        g_nev = [float(x) for x in g.groups()] if g else None
    version = re.search(r"Program Version (\S+)", text)
    return {
        "d_count": int(head.group(1)), "n_active": int(mos.group(2)) - int(mos.group(1)) + 1 if mos else None,
        "phases": [float(x) for x in phases.group(1).split()] if phases else None, "n_shells": len(shells),
        "dparts": dparts if len(shells) else None, "sections": sections, "roots_eh": roots, "nevpt2_roots_eh": nev_roots, "soc": soc, "g_nevpt2": g_nev,
        "terminated": "ORCA TERMINATED NORMALLY" in text, "converged": "THE CAS-SCF GRADIENT HAS CONVERGED" in text,
        "version": version.group(1) if version else None,
    }


def _lf_matrix(eigvec, energies) -> np.ndarray:
    """V = C^T diag(E) C from the printed LF eigenfunctions (rows), re-orthonormalised (nearest orthogonal) to remove rounding."""
    u, _s, vt = np.linalg.svd(np.asarray(eigvec, dtype=float))
    c = u @ vt
    return c.T @ np.diag(np.asarray(energies, dtype=float)) @ c


def ailft_problems(parsed: dict, d_count: int, need_nevpt2: bool = False) -> list[str]:
    problems = []
    if not parsed["terminated"]:
        problems.append("ORCA did not terminate normally")
    if not parsed["converged"]:
        problems.append("CASSCF not converged ('THE CAS-SCF GRADIENT HAS CONVERGED' missing)")
    if parsed["d_count"] != d_count:
        problems.append(f"AILFT treats a d{parsed['d_count']} configuration, expected d{d_count} (wrong active space: check the AVAS "
                        "selection 'AVAS electrons/orbitals' of the reference)")
    if parsed["n_active"] not in (None, 5):
        problems.append(f"{parsed['n_active']} active orbitals, expected the 5 metal d")
    if parsed["phases"] is not None and any(abs(p - 1.0) > 1e-6 for p in parsed["phases"]):
        problems.append(f"AILFT adjusted orbital phases {parsed['phases']}: the re-alignment is validated only for phases +1")
    if parsed["dparts"] is None:
        problems.append("no metal d-orbital parts printed")
    if parsed["soc"] is None:
        problems.append("no ab initio SOC matrices (rel dosoc true)")
    if "CASSCF" not in parsed["sections"]:
        problems.append("no AILFT (CASSCF) section")
    if need_nevpt2 and "NEVPT2" not in parsed["sections"]:
        problems.append("no AILFT (NEVPT2) section (ptmethod sc_nevpt2)")
    return problems


def realigned_point(path, d_count: int, need_nevpt2: bool = False) -> dict[str, Any]:
    """V_LF (CASSCF; NEVPT2 when present) and h_k of one output in the re-aligned (ideal-d) basis; raises on an unusable point."""
    parsed = parse_ailft_output(path)
    problems = ailft_problems(parsed, d_count, need_nevpt2)
    if problems:
        raise ValueError("; ".join(problems))
    s = parsed["dparts"]
    w, u = np.linalg.eigh(s @ s.T)
    t = s.T @ (u @ np.diag(w**-0.5) @ u.T)  # chi = phi T: symmetric orthonormalisation onto the ideal d functions
    table, vec = parsed["sections"]["CASSCF"]
    out = {"V_casscf": t.T @ _lf_matrix(vec, _orbital_energies(parsed["roots_eh"], table, d_count, "CASSCF")) @ t,
           "h": np.einsum("im,kij,jn->kmn", t, parsed["soc"], t),
           "energy_eh": float(parsed["roots_eh"][0]) if len(parsed["roots_eh"]) else None, "version": parsed["version"],
           "d_singular_values": np.linalg.svd(s, compute_uv=False), "g_nevpt2": parsed["g_nevpt2"]}
    if "NEVPT2" in parsed["sections"]:
        table, vec = parsed["sections"]["NEVPT2"]
        out["V_nevpt2"] = t.T @ _lf_matrix(vec, _orbital_energies(parsed["nevpt2_roots_eh"], table, d_count, "NEVPT2")) @ t
    return out


def _orbital_energies(roots_eh, table, d_count: int, level: str) -> np.ndarray:
    """LF orbital energies (ascending, lowest 0) from the 5 root energies (CASSCF 1e-10 Eh, NEVPT2 E0+dE 1e-14 Eh) instead of the
    0.1 cm-1 AILFT table, which finite differences cannot use; checked against the table. d9: root i = hole in orbital i."""
    if len(roots_eh) != 5:
        return np.asarray(table, dtype=float)
    e = (np.asarray(roots_eh) - min(roots_eh)) * EH_TO_CM1
    energies = np.sort(e) if d_count == 1 else np.sort(e.max() - e)
    if np.abs(energies - table).max() > 1.0:
        raise ValueError(f"{level} roots and the AILFT orbital energies disagree by {np.abs(energies - table).max():.2f} cm-1")
    return energies


def reference_problems(path, d_count: int) -> list[str]:
    """Why a CASSCF/NEVPT2 + AILFT reference output cannot anchor a Gamma_II sweep ([] = usable)."""
    path = Path(path)
    if not path.is_file():
        return [f"{path.name} not found: run the reference (orca/reference.inp) before preparing the sweep"]
    try:
        return ailft_problems(parse_ailft_output(path), d_count, need_nevpt2=True)
    except (ValueError, StopIteration, IndexError) as exc:
        return [f"{path.name}: {exc}"]


# --------------------------------------------------------------------------- #
# Geometry: metal frame, directions, steps
# --------------------------------------------------------------------------- #


def molecular_frame(positions, metal: int, donors) -> tuple[np.ndarray, float]:
    """R (rows = new x, y, z in the input frame) and how distinct z is (0 = no unique axis). z = the donors' most distinct
    second-moment axis about the metal, snapped onto the axial bond(s) within 30 deg of it (V=O; trans axial pair), towards the
    donor farthest along it; x = the in-plane donor directions averaged four-fold (along the bonds of a square plane)."""
    r = np.asarray(positions, dtype=float)[list(donors)] - np.asarray(positions, dtype=float)[metal]
    lam, vec = np.linalg.eigh(r.T @ r)
    dev = np.array([abs(lam[i] - (lam.sum() - lam[i]) / 2) for i in range(3)])
    z = vec[:, int(np.argmax(dev))]
    unit = r / np.linalg.norm(r, axis=1)[:, None]
    axial = np.abs(unit @ z) > math.cos(math.radians(30.0))
    if axial.any():  # VOPc: the second-moment axis is 1.6 deg off V=O, which ORCA's g_par axis follows to 0.2 deg
        z = (np.sign(unit[axial] @ z)[:, None] * unit[axial]).sum(axis=0)
        z /= np.linalg.norm(z)
    along = r @ z
    z = z if along[np.argmax(np.abs(along))] >= 0 else -z
    inplane = r - np.outer(r @ z, z)
    eq = np.linalg.norm(inplane, axis=1) > 0.5 * np.linalg.norm(r, axis=1)
    ref = inplane[int(np.argmax(eq))] if eq.any() else np.cross(z, np.eye(3)[int(np.argmin(np.abs(z)))])
    ref = ref / np.linalg.norm(ref)
    side = np.cross(z, ref)
    phi = np.arctan2(inplane[eq] @ side, inplane[eq] @ ref)
    phi0 = float(np.angle(np.exp(4j * phi).sum()) / 4) if eq.any() else 0.0
    x = math.cos(phi0) * ref + math.sin(phi0) * side
    return np.vstack([x, np.cross(z, x), z]), float(dev.max() / max(lam.sum(), 1e-12))


def span_directions(vectors, freqs, soft_cutoff: float, extension_weight: float) -> tuple[np.ndarray, list[str], np.ndarray]:
    """Orthonormal mass-weighted directions (rows): the exact span of the modes <= soft_cutoff, then the directions holding
    extension_weight of the higher modes' weight outside it. Also the block of each direction and its relative singular value."""
    vectors, freqs = np.asarray(vectors, dtype=float), np.asarray(freqs, dtype=float)
    dirs, blocks, sv = np.zeros((0, vectors.shape[1])), [], []
    soft = freqs <= soft_cutoff
    if soft.any():
        u, s, _ = np.linalg.svd(vectors[soft].T, full_matrices=False)
        keep = s >= SOFT_RCOND * s.max()
        dirs, blocks, sv = u[:, keep].T, ["soft"] * int(keep.sum()), list(s[keep] / s.max())
    if (~soft).any():
        rest = vectors[~soft] - (vectors[~soft] @ dirs.T) @ dirs
        u, s, _ = np.linalg.svd(rest.T, full_matrices=False)
        if s.max() > 1e-8:
            n = min(int(np.searchsorted(np.cumsum(s**2) / np.sum(s**2), extension_weight) + 1), len(s))
            ext = u[:, :n].T
            ext = np.linalg.qr((ext - (ext @ dirs.T) @ dirs).T)[0].T
            dirs, blocks, sv = np.vstack([dirs, ext]), blocks + ["extension"] * n, sv + list(s[:n] / s[0])
    return dirs, blocks, np.array(sv)


def _write_xyz(path: Path, symbols, xyz, comment: str) -> None:
    path.write_text(f"{len(symbols)}\n{comment}\n" + "".join(f"{s:<3}{p[0]:20.12f}{p[1]:20.12f}{p[2]:20.12f}\n" for s, p in zip(symbols, xyz)))


def orca_inputs(symbols, xyz, charge: int, d_count: int, tz_elements, nprocs: int, avas_threshold: float,
                member_level: str = "nevpt2") -> dict[str, str]:
    """start_orbitals.inp (ROHF), reference.inp (CASSCF(n,5)/SC-NEVPT2 + AI-SOC, AVAS on the ROHF orbitals) and
    sweep_template.inp (the reference without the guess, and without NEVPT2 when member_level='casscf'):
    prepare_orca_displacement_sweep clones it."""
    if member_level not in MEMBER_LEVELS:
        raise ValueError(f"member_level must be one of {MEMBER_LEVELS}")
    mult = min(d_count, 10 - d_count) + 1
    basis = "%basis\n" + "".join(f'  NewGTO {e} "def2-TZVP" end\n' for e in tz_elements)
    geometry = f"* xyz {charge} {mult}\n" + "".join(f"{s:<3}{p[0]:18.10f}{p[1]:18.10f}{p[2]:18.10f}\n" for s, p in zip(symbols, xyz)) + "*\n"
    casscf = (f"%casscf\n  nel {d_count}\n  norb 5\n  mult {mult}\n  nroots 5\n  actorbs dorbs\n  etol 1e-10\n  gtol 5e-5\n  maxiter 60\n"
              "{pt}  rel\n    dosoc true\n    gtensor true\n  end\nend\n")
    aux = '  AuxJ  "def2/J"\n  AuxJK "def2/JK"\n  AuxC  "def2-TZVP/C"\nend\n'
    return {
        "start_orbitals.inp": (f"# Gamma_II start orbitals: ROHF in the CASSCF basis (reference.inp projects the metal d shell out of them with AVAS)\n"
                               f"! ROHF def2-SVP def2/J RIJCOSX TightSCF\n{basis}end\n%pal nprocs {nprocs} end\n%maxcore 3500\n"
                               f"%scf\n  MaxIter 300\nend\n{geometry}"),
        "reference.inp": (f"# Gamma_II reference (Mariano/Lunghi 2024): SA-CASSCF(d{d_count}: {d_count},5) over the 5 doublets / SC-NEVPT2, AILFT\n"
                          "# (actorbs dorbs), ab initio SOC (RI-SOMF(1X)); start: AVAS(Valence-D) on start_orbitals.gbw (run start_orbitals.inp first,\n"
                          "# same folder). Check 'AVAS electrons/orbitals' = d count / 5; otherwise re-export with another avas_threshold.\n"
                          f"! def2-SVP RIJK RI-SOMF(1X) VeryTightSCF MORead AVAS(Valence-D)\n%moinp \"start_orbitals.gbw\"\n{basis}{aux}"
                          f"%pal nprocs {2 * nprocs} end\n%maxcore 3500\n%scf\n  avas\n    tol {avas_threshold:g}\n  end\nend\n"
                          + casscf.format(pt="  ptmethod sc_nevpt2\n") + geometry),
        "sweep_template.inp": (f"# Gamma_II sweep protocol ({member_level} members): the reference's CASSCF{'/SC-NEVPT2' if member_level == 'nevpt2' else ''} "
                               "+ SOC + AILFT without the guess (members MORead reference.gbw)\n"
                               f"! def2-SVP RIJK RI-SOMF(1X) VeryTightSCF\n{basis}{aux}%pal nprocs {nprocs} end\n%maxcore 3500\n"
                               + casscf.format(pt="  ptmethod sc_nevpt2\n" if member_level == "nevpt2" else "") + geometry),
    }


def export_excited_state_displacements(
    cluster_manifest: Annotated[str, "cluster_manifest.json of the cluster carved around the METAL (extract_molecular_cluster_from_crystal on the phonon reference cell, center = the metal)."],
    phonon_dir: Annotated[str, "Crystal phonon directory (phonopy_params.yaml; primitive = the unit cell the cluster was carved from)."],
    oxidation_state: Annotated[int, "Metal oxidation state: d count = group - oxidation state (V(IV) d1 -> CAS(1,5); Cu(II) d9 -> CAS(9,5)). d1 and d9 only."],
    mode_cutoff_cm1: Annotated[float, "Gamma modes up to this frequency are spanned (VOPc: modes 150-400 cm-1 carry ~95% of the 300 K Gamma_II rate; 150 cm-1 alone gives a 23x too long T1)."] = 500.0,
    soft_cutoff_cm1: Annotated[float, "Modes up to this frequency are spanned exactly; the rest to extension_weight of their remaining weight."] = 150.0,
    extension_weight: Annotated[float, "Fraction of the higher modes' weight outside the soft span that the extra directions hold."] = 0.99,
    step_angstrom: Annotated[float, "Finite-difference step: rms displacement of the metal + donor atoms (A)."] = 0.01,
    max_atom_displacement_angstrom: Annotated[float, "No atom moves more than this at the +/-Q step (A); the step is scaled down to it."] = 0.05,
    linearity_directions: Annotated[int, "The first N directions also get +/-2Q members (linearity check in collect_excited_state_couplings)."] = 4,
    nprocs: Annotated[int, "Cores per sweep member (the NEVPT2 reference gets twice as many)."] = 8,
    avas_threshold: Annotated[float, "AVAS selection threshold of the reference (VOPc: 0.45 picked (3,6), 0.5 the d shell)."] = 0.5,
    member_level: Annotated[str, MEMBER_LEVEL_DOC] = "nevpt2",
    output_dir: Annotated[str, "Default <cluster folder>/excited_state_displacements."] = "",
    gamma_modes_json: Annotated[str, "Instead of phonon_dir (pass phonon_dir=''): gamma_modes.json of molecule_gamma_modes_from_hess, the "
                                     "isolated molecule's normal modes; carve the cluster from its molecule_box.extxyz."] = "",
    runtime: ToolRuntime = None,
) -> Dict[str, Any]:
    """Gamma_II (excited-state two-phonon) sweep of the central molecule: the ORCA start-orbital / CASSCF-NEVPT2 reference /
    sweep-template inputs and +/-Q members along orthonormal molecular directions spanning the crystal's Gamma modes up to
    mode_cutoff_cm1, in a metal frame (z = metal axis). Feed the manifest to prepare_orca_displacement_sweep with
    orca/sweep_template.inp and reference_gbw=orca/reference.gbw, then collect_excited_state_couplings."""
    root = _h._root(runtime)
    try:
        from ase.data import atomic_numbers

        gs = sr.load_gamma_set(root, phonon_dir, gamma_modes_json)
        prov = gs.ph_dir / "fc_provenance.json" if gs.ph_dir else None  # MLIP / mixed force-constant builders; DFT phonopy sets have none
        phonon_source = (json.loads(prov.read_text()).get("force_constants_source") if prov and prov.is_file()
                         else gs.low_mode.get("force_constants_source") if gs.low_mode else None)
        mpath, man, cluster, origin, chosen = cp._cluster_selection(root, cluster_manifest, "molecule", "")
        shell = cp._cluster_selection(root, cluster_manifest, "first_shell", "")[4]
        if int(man["cell_atoms"]) != len(gs.masses):
            raise ValueError(f"The cluster was carved from a {man['cell_atoms']}-atom cell but the phonon cell has {len(gs.masses)} atoms.")
        metal = shell[0]
        element = cluster[metal].symbol
        z_num = atomic_numbers[element]
        if not 21 <= z_num <= 30:
            raise ValueError(f"The cluster is centred on {element}, not a 3d metal: carve it with center = the metal's cell index.")
        d_count = (z_num - 18) - int(oxidation_state)
        if d_count not in SUPPORTED_D_COUNTS:
            raise ValueError(f"{element}({int(oxidation_state)}) is d{d_count}: the Gamma_II model needs an S = 1/2 d1 (one electron) or d9 (one hole) ion.")
        if len(shell) < 2:
            raise ValueError(f"No donor atom bonded to {element} in the central molecule.")
        cell_atoms = [int(origin[k][0]) for k in chosen]
        deviation = cp.molecule_positions_in_phonon_cell(gs.phonon, cluster.positions[chosen], cell_atoms)[1]
        local = {k: i for i, k in enumerate(chosen)}
        metal_i, donors = local[metal], [local[k] for k in shell[1:]]
        symbols = [cluster[k].symbol for k in chosen]
        masses = gs.masses[cell_atoms]
        rot, distinct = molecular_frame(cluster.positions[chosen], metal_i, donors)
        xyz = (cluster.positions[chosen] - cluster.positions[metal]) @ rot.T
        modes = [int(i) for i in np.argsort(gs.freqs) if i not in gs.acoustic and i not in gs.suspect and 0 < gs.freqs[i] <= float(mode_cutoff_cm1)]
        if not modes:
            raise ValueError(f"No real optical Gamma mode up to {mode_cutoff_cm1:g} cm-1.")
        freqs = gs.freqs[modes]
        rows = np.ravel([[3 * c, 3 * c + 1, 3 * c + 2] for c in cell_atoms])
        e, t = gs.vecs[rows][:, modes], translations(masses)
        vec = (e - t @ (t.T @ e)).T  # (n, 3m): the molecule's rows of each mode, its net mass-weighted translation removed
        vec = (vec.reshape(len(modes), -1, 3) @ rot.T).reshape(len(modes), -1)  # into the metal frame
        dirs, blocks, sv = span_directions(vec, freqs, float(soft_cutoff_cm1), float(extension_weight))
        coverage = ((vec @ dirs.T) ** 2).sum(axis=1) / (vec**2).sum(axis=1)
        inv_sqm = np.repeat(1.0 / np.sqrt(masses), 3)
        out = _h._under_root(root, _h._resolve_path(root, output_dir) if output_dir.strip() else mpath.parent / "excited_state_displacements")
        (out / "displaced_xyz").mkdir(parents=True, exist_ok=True)
        (out / "orca").mkdir(exist_ok=True)
        _write_xyz(out / "reference.xyz", symbols, xyz, f"{element} d{d_count} reference, metal frame (metal at origin, z = metal axis)")
        steps, pairs, members = [], [], []
        for j, u in enumerate(dirs):
            d = (u * inv_sqm).reshape(-1, 3)  # A per unit Q (amu^1/2 A)
            fs_rms = math.sqrt(float((d[[metal_i] + donors] ** 2).sum(axis=1).mean()))
            dmax = float(np.linalg.norm(d, axis=1).max())
            q = min(float(step_angstrom) / fs_rms, float(max_atom_displacement_angstrom) / dmax)
            steps.append({"direction": j, "block": blocks[j], "singular_value_rel": round(float(sv[j]), 6), "q": q,
                          "first_shell_rms_angstrom": round(q * fs_rms, 6), "max_atom_displacement_angstrom": round(q * dmax, 6),
                          "capped": bool(q * fs_rms < float(step_angstrom) - 1e-12)})
            for multiple in (1, 2) if j < int(linearity_directions) else (1,):
                pair = len(pairs)
                pairs.append({"pair": pair, "direction": j, "multiple": multiple, "q": multiple * q})
                for sign, tag in ((1, "plus"), (-1, "minus")):
                    label = f"dir{j:03d}_x{multiple}_{tag}"
                    disp = sign * multiple * q * d
                    _write_xyz(out / "displaced_xyz" / f"{label}.xyz", symbols, xyz + disp, f"direction {j} Q = {sign * multiple * q:.8f} amu^1/2 A")
                    members.append({"member": label, "pair": pair, "sign": sign, "direction": j, "multiple": multiple,
                                    "q": sign * multiple * q, "displacement": np.round(disp, 12).tolist(), "qm_xyz": f"displaced_xyz/{label}.xyz"})
        tz = [element] + sorted({symbols[i] for i in donors} - {element})
        inputs = orca_inputs(symbols, xyz, int(man["qm_molecules"][0]["charge"]), d_count, tz, int(nprocs), float(avas_threshold), member_level)
        embedding = None
        pc_rel = man.get("pointcharge_file") or (str(Path(man["qm_xyz"]).with_suffix(".pc")) if man.get("qm_xyz") else "")
        if pc_rel and (root / pc_rel).is_file():  # the carve writes <label>.pc beside <label>.xyz (same frame)
            man = {**man, "pointcharge_file": pc_rel}
            # The carve's embedding (point_charges / ewald_fit) is in the cluster frame: map it exactly like the QM atoms. Charged
            # clusters need it (campaign rule 2026-10-08): a bare dianion has raised, diffuse levels. The charges stay fixed in members.
            pc_lines = _h._resolve_path(root, man["pointcharge_file"], must_exist=True, dir_ok=False).read_text().split("\n")
            pc = np.array([[float(v) for v in line.split()[:4]] for line in pc_lines[1:1 + int(pc_lines[0].split()[0])]])
            pos = (pc[:, 1:] - cluster.positions[metal]) @ rot.T
            (out / "orca" / "embedding.pc").write_text(f"{len(pc)}\n" + "".join(f"{q:14.8f}{p[0]:16.8f}{p[1]:16.8f}{p[2]:16.8f}\n" for q, p in zip(pc[:, 0], pos)))
            inputs = {name: text.replace("%pal", '%pointcharges "embedding.pc"\n%pal', 1) for name, text in inputs.items()}
            embedding = {"pointcharge_file": "orca/embedding.pc", "n_charges": int(len(pc)), "total_charge": round(float(pc[:, 0].sum()), 6),
                         "mode": (man.get("embedding") or {}).get("mode", "point_charges"), "source": man["pointcharge_file"]}
        for name, text in inputs.items():
            (out / "orca" / name).write_text(text)
        bands = {}
        for lo, hi in ((0, soft_cutoff_cm1), (soft_cutoff_cm1, 300.0), (300.0, mode_cutoff_cm1)):
            sel = (freqs > lo) & (freqs <= hi)
            if sel.any() and hi > lo:
                bands[f"{lo:g}-{hi:g}"] = {"n_modes": int(sel.sum()), "min": round(float(coverage[sel].min()), 4), "mean": round(float(coverage[sel].mean()), 4)}
        manifest = {
            "kind": KIND, "reference_cluster": "reference.xyz", "reference_manifest": _h._rel(root, mpath),
            "phonon_dir": _h._rel(root, gs.ph_dir) if gs.ph_dir else None, "gamma_modes_json": _h._rel(root, gs.path) if gs.low_mode else None,
            "phonon_set_sha256": gs.sha256, "phonon_source": phonon_source, "embedding": embedding,
            "metal": element, "oxidation_state": int(oxidation_state),
            "d_count": d_count, "charge": int(man["qm_molecules"][0]["charge"]), "multiplicity": min(d_count, 10 - d_count) + 1, "member_level": member_level,
            "metal_index": metal_i, "donors": donors, "symbols": symbols, "masses_amu": masses.tolist(), "positions_angstrom": xyz.tolist(),
            "atoms": [{"cluster_atom": int(k), "cell_atom": c, "element": s} for k, c, s in zip(chosen, cell_atoms, symbols)],
            "frame": {"rotation_rows_new_axes": rot.tolist(), "origin": f"{element} (cluster atom {metal})", "axis_distinctness": round(distinct, 4),
                      "rule": "r_frame = R (r_cluster - r_metal); vectors v_frame = R v_cluster; z = metal axis"},
            "mapping_max_deviation_angstrom": round(deviation, 5), "mode_cutoff_cm1": float(mode_cutoff_cm1), "soft_cutoff_cm1": float(soft_cutoff_cm1),
            "extension_weight": float(extension_weight), "step_angstrom": float(step_angstrom), "max_atom_displacement_angstrom": float(max_atom_displacement_angstrom),
            "directions_mass_weighted": dirs.tolist(), "steps": steps, "pairs": pairs,
            "modes": {"indices": modes, "frequencies_cm1": freqs.tolist(), "vectors_mass_weighted": vec.tolist(), "coverage": coverage.tolist(),
                      "weight_on_molecule": (vec**2).sum(axis=1).tolist()},
            "members": members, "inputs": {name: f"orca/{name}" for name in inputs},
            "displacement_convention": "member geometry = reference + q u_j / sqrt(m) (u_j: directions_mass_weighted row j, metal frame); "
                                       "q = +/-multiple x steps[j].q (amu^1/2 A); displacement lists every atom of the molecule",
        }
        (out / MANIFEST_NAME).write_text(json.dumps(manifest))
        n_jobs = len(members) + 1
        mlip = bool(phonon_source and phonon_source.startswith("MLIP"))
        result = {"ok": True, "manifest": _h._rel(root, out / MANIFEST_NAME), "metal": element, "d_count": d_count,
                  "active_space": f"CAS({d_count},5), multiplicity {manifest['multiplicity']}, 5 roots", "charge": manifest["charge"],
                  "n_atoms": len(chosen), "n_modes": len(modes), "n_directions": len(dirs), "n_soft_directions": blocks.count("soft"),
                  "n_linearity_directions": min(int(linearity_directions), len(dirs)), "sweep_jobs": n_jobs,
                  "coverage_by_band": bands, "frame_axis_distinctness": round(distinct, 4),
                  "step_q_range": [round(min(s["q"] for s in steps), 5), round(max(s["q"] for s in steps), 5)],
                  "inputs": {name: _h._rel(root, out / "orca" / name) for name in inputs},
                  "cost_note": f"{n_jobs} {member_level.upper()} members + 2 reference jobs; VOPc (58 atoms, 8 cores, node-local scratch): "
                               "~3.8 core-h per NEVPT2 member, ~1.4 per CASSCF member, ~8 core-h for the NEVPT2 reference (16 cores); VO(acac)2 (30 atoms): ~0.3 / ~0.2",
                  "next_steps": [f"run {_h._rel(root, out / 'orca' / 'start_orbitals.inp')}, then reference.inp in the same folder (it reads start_orbitals.gbw)",
                                 f"prepare_orca_displacement_sweep(reference_input='{_h._rel(root, out / 'orca' / 'sweep_template.inp')}', "
                                 f"displacement_manifest='{_h._rel(root, out / MANIFEST_NAME)}', reference_gbw='{_h._rel(root, out / 'orca' / 'reference.gbw')}')",
                                 "submit_orca_displacement_sweep (dry_run, then submit after approval)",
                                 "collect_excited_state_couplings(<orca_sweep_manifest.json>)",
                                 "compute_excited_state_spin_relaxation(<couplings json>, spin_relaxation_json=<compute_spin_relaxation_time output>)"]}
        if distinct < 0.05:
            result["warning_frame"] = "No distinct metal axis (near-cubic first shell): z is arbitrary, so the B||axis anisotropy is not meaningful."
        result["phonon_source"] = phonon_source or "DFT phonopy set (no fc_provenance.json)"
        result["embedding"] = embedding or "none (bare cluster)"
        if embedding is None and int(man["qm_molecules"][0]["charge"]) != 0:
            result["warning_embedding"] = ("Charged cluster without embedding: carve it with embedding='ewald_fit' "
                                           "(extract_molecular_cluster_from_crystal) so the ORCA inputs carry the crystal field.")
        if mlip:
            result["note_mlip_prescreen"] = MLIP_PRESCREEN_NOTE
        if float(coverage.min()) < 0.9:
            result["warning_coverage"] = f"Some modes lie < 90% inside the span (min {coverage.min():.3f}): raise extension_weight."
        return result
    except Exception as exc:
        return _h._error(exc)


# --------------------------------------------------------------------------- #
# Couplings from the finished sweep
# --------------------------------------------------------------------------- #


def libration_check(positions, masses, directions, dv, dh, v0, h0) -> list[dict[str, Any]]:
    """Rigid rotation of the molecule about each frame axis: the finite-difference coupling along the part of the rotation inside
    the span vs -i[J_k, H] (the exact libration coupling of a rotation-covariant basis)."""
    pos, m = np.asarray(positions, dtype=float), np.asarray(masses, dtype=float)
    rc = pos - (m[:, None] * pos).sum(axis=0) / m.sum()
    h_ref = one_electron(v0, h0)
    rows = []
    for k in range(3):
        r = (np.cross(np.eye(3)[k], rc) * np.sqrt(m)[:, None]).ravel()  # mass-weighted displacement per radian
        proj = np.asarray(directions) @ r
        fd = one_electron(np.einsum("j,jmn->mn", proj, dv), np.einsum("j,jkmn->kmn", proj, dh))
        exact = -1j * (J_FULL[k] @ h_ref - h_ref @ J_FULL[k])
        rows.append({"axis": "xyz"[k], "span_coverage": round(float(proj @ proj / (r @ r)), 6),
                     "relative_error": round(float(np.linalg.norm(fd - exact) / np.linalg.norm(exact)), 5)})
    return rows


def _central(fd, q, key: str, multiple: int = 1):
    """Central differences (n_dir, 5, 5) of V (key) and (n_dir, 3, 5, 5) of h along every direction with that step multiple."""
    js = sorted(j for j, m in fd if m == multiple)
    dv = np.array([(fd[(j, multiple)][0][key] - fd[(j, multiple)][1][key]) / (2 * multiple * q[j]) for j in js])
    dh = np.array([(fd[(j, multiple)][0]["h"] - fd[(j, multiple)][1]["h"]) / (2 * multiple * q[j]) for j in js])
    return js, dv, dh


def couplings_from_points(manifest: dict, reference: dict, fd: dict, sweep_reference: dict | None = None, repeats=()) -> dict[str, Any]:
    """Finite-difference vibronic couplings per direction and per Gamma mode, with linearity, noise and libration checks.
    reference: realigned_point of the NEVPT2 reference run; fd[(direction, multiple)] = (plus, minus) realigned points;
    sweep_reference: the sweep's undisplaced member; repeats: reference-geometry runs from other starting orbitals.
    Couplings level: 'nevpt2' (NEVPT2 AILFT matrices at every member, consistent with the NEVPT2 levels) or, for CASSCF members,
    'nevpt2_constshift' (nevpt2_constant_shift); the CASSCF couplings (mixed scheme) are kept as a sensitivity."""
    dirs = np.array(manifest["directions_mass_weighted"], dtype=float)
    q = np.array([s["q"] for s in manifest["steps"]], dtype=float)
    missing = [j for j in range(len(dirs)) if (j, 1) not in fd]
    if missing:
        raise ValueError(f"directions {missing} have no usable +/-Q pair")
    if all("V_nevpt2" in x for pair in fd.values() for x in pair):
        level, key = "nevpt2", "V_nevpt2"
    else:  # CASSCF members: carry the reference's NEVPT2 level shifts on each point's CASSCF LF eigenvectors
        level, key = "nevpt2_constshift", "V_nevpt2_constshift"
        shift = nevpt2_level_shifts(reference)
        fd = {k: tuple(nevpt2_constant_shift(x, shift) for x in pair) for k, pair in fd.items()}
        if sweep_reference is not None:
            sweep_reference = nevpt2_constant_shift(sweep_reference, shift)
    _js, dv, dh = _central(fd, q, key)
    _js, dv_cas, _dh = _central(fd, q, "V_casscf")
    linearity = []
    js2, dv2, dh2 = _central(fd, q, key, 2) if any(m == 2 for _j, m in fd) else ([], [], [])
    for j, a, b in zip(js2, dv2, dh2):
        linearity.append({"direction": j, "rel_diff_V": round(float(np.linalg.norm(dv[j] - a) / np.linalg.norm(dv[j])), 6),
                          "rel_diff_h": round(float(np.linalg.norm(dh[j] - b) / max(np.linalg.norm(dh[j]), 1e-300)), 6),
                          "max_abs_dV_cm1_per_q": round(float(np.abs(dv[j]).max()), 3)})
    vecs = np.array(manifest["modes"]["vectors_mass_weighted"], dtype=float)
    c = vecs @ dirs.T
    coverage = (c**2).sum(axis=1) / (vecs**2).sum(axis=1)
    noise: dict[str, Any] = {"independent_repeats": len(repeats)}
    if repeats:
        rkey = key if all(key in r for r in [reference, *repeats]) else "V_casscf"
        runs = [reference] + list(repeats)
        sv = np.array([r[rkey] for r in runs]).std(axis=0, ddof=1)
        sh = np.array([r["h"] for r in runs]).std(axis=0, ddof=1)
        noise.update({"level": rkey[2:], "V_std_max_cm1": float(sv.max()), "V_std_rms_cm1": float(np.sqrt((sv**2).mean())), "h_std_max_cm1": float(sh.max()),
                      "derivative_noise_to_signal": [round(float(math.sqrt(2) * np.sqrt((sv**2).sum()) / (2 * q[j]) / np.linalg.norm(dv[j])), 5)
                                                     for j in range(len(dirs))]})
    else:
        noise["note"] = "no independent repeats: pass repeat_outputs (reference geometry restarted from other orbitals) to measure it"
    if sweep_reference is not None:
        noise["sweep_reference_vs_reference_run_max_dV_cm1"] = float(np.abs(sweep_reference[key] - reference["V_nevpt2"]).max())
    levels = {"casscf": np.linalg.eigvalsh(reference["V_casscf"]).tolist(), "nevpt2": np.linalg.eigvalsh(reference["V_nevpt2"]).tolist()}
    mode = lambda d: np.einsum("aj,jmn->amn", c, d).tolist()  # noqa: E731
    return {
        "kind": COUPLINGS_KIND, "d_count": int(manifest["d_count"]), "metal": manifest.get("metal"), "frame": manifest.get("frame"),
        "phonon_source": manifest.get("phonon_source"),
        "unit": "cm-1; couplings per amu^1/2 A", "lf_levels_cm1": levels, "couplings_level": level,
        "reference": {"V_nevpt2": reference["V_nevpt2"].tolist(), "V_casscf": reference["V_casscf"].tolist(), "h_soc": reference["h"].tolist(),
                      "orca_g_nevpt2": reference.get("g_nevpt2")},
        "modes": {"indices": manifest["modes"].get("indices"), "frequencies_cm1": manifest["modes"]["frequencies_cm1"], "coverage": coverage.tolist()},
        "mode_couplings": {"dV": mode(dv), "dh": np.einsum("aj,jkmn->akmn", c, dh).tolist()},
        "mode_couplings_casscf_dV": mode(dv_cas),
        "direction_couplings": {"dV": dv.tolist(), "dh": dh.tolist()},
        "checks": {"linearity": linearity, "noise": noise,
                   "libration": libration_check(manifest["positions_angstrom"], manifest["masses_amu"], dirs, dv, dh, reference["V_nevpt2"], reference["h"])},
    }


def nevpt2_level_shifts(reference: dict, degenerate_cm1: float = 100.0) -> np.ndarray:
    """NEVPT2 - CASSCF energy of each reference CASSCF LF eigenvector (indexed in ascending CASSCF order), averaged over levels
    closer than degenerate_cm1 so the shift does not depend on how a near-degenerate pair's eigenvectors rotate between geometries
    (VOPc e pair: 26 cm-1 apart, shifts 5384 / 5377 cm-1). Paired by eigenvector, not by rank: NEVPT2 can reorder the levels
    (VO(acac)2 at its crystal geometry: CASSCF e < b1, NEVPT2 b1 < e; rank pairing put the levels up to 720 cm-1 off the NEVPT2
    reference and T1(300 K) 24% short; paired by eigenvector, T1 is within 7% of NEVPT2 members)."""
    from scipy.optimize import linear_sum_assignment

    e_cas, w_cas = np.linalg.eigh(reference["V_casscf"])
    e_nev, w_nev = np.linalg.eigh(reference["V_nevpt2"])
    _rows, match = linear_sum_assignment(-((w_cas.T @ w_nev) ** 2))  # ORCA's NEVPT2 AILFT keeps the CASSCF eigenvectors (overlap 1)
    shift, start = e_nev[match] - e_cas, 0
    for k in range(1, len(e_cas) + 1):
        if k == len(e_cas) or e_cas[k] - e_cas[k - 1] > degenerate_cm1:
            shift[start:k] = shift[start:k].mean()
            start = k
    return shift


def nevpt2_constant_shift(point: dict, shift) -> dict:
    """V_nevpt2(q) ~ V_casscf(q) + W(q)^T diag(shift) W(q), W = the point's CASSCF LF eigenvectors, shift = the reference's NEVPT2 -
    CASSCF orbital energies. ORCA's NEVPT2 AILFT keeps the CASSCF eigenvectors, so only the diagonal level modulation d(shift)/dq is
    dropped, which reaches the ground-excited couplings Gamma_II uses only through SOC mixing (VOPc, 12 directions: 0.01-0.1%; T1
    within 1% of NEVPT2 members). The mixed scheme (CASSCF couplings with NEVPT2 levels) underestimates them by 21-23%."""
    _e, w = np.linalg.eigh(point["V_casscf"])
    return {**point, "V_nevpt2_constshift": point["V_casscf"] + w @ np.diag(shift) @ w.T}


def lf_consistency_adjudication(manifest: dict, by_pair: dict, points: dict, flags: dict, energy_flags: dict, r0: dict) -> dict:
    """Energy-guard flags judged by the d manifold, not the total energy. A member off the reference energy (CuOEP: +5..+10 mEh, a
    tightly converged CASSCF in another INACTIVE-orbital solution) is kept when its +/-Q pair's largest LF-diagonal second
    difference |V+ + V- - 2 V0| is no larger than every clean pair's at the same step multiple (CuOEP, 9 flagged members: 0.3-5.0 cm-1
    vs clean median 2.0, max 12.5; couplings identical to the hand adjudication; a member in another d solution jumps by hundreds).
    Returns {label: evidence} for the kept members."""
    def second_difference(labels):
        vp, vm = (points[lab]["V_casscf"] for lab in labels)
        return float(np.abs(np.diag(vp + vm - 2 * r0["V_casscf"])).max())

    pairs = {(pr["direction"], pr["multiple"]): [by_pair.get((pr["pair"], s), "") for s in ("plus", "minus")] for pr in manifest["pairs"]}
    usable = {k: labs for k, labs in pairs.items() if all(lab in points and not flags.get(lab) for lab in labs)}
    clean: dict[int, list[float]] = {}
    for (_j, m), labs in usable.items():
        if not any(lab in energy_flags for lab in labs):
            clean.setdefault(m, []).append(second_difference(labs))
    kept = {}
    for (j, m), labs in usable.items():
        hit = [lab for lab in labs if lab in energy_flags]
        if hit and clean.get(m) and second_difference(labs) <= max(clean[m]):
            for lab in hit:
                kept[lab] = {"flag": energy_flags[lab], "direction": j, "multiple": m,
                             "lf_second_difference_cm1": round(second_difference(labs), 2), "clean_max_cm1": round(max(clean[m]), 2),
                             "clean_median_cm1": round(float(np.median(clean[m])), 2)}
    return kept


def step_test_adjudication(manifest: dict, by_pair: dict, points: dict, flags: dict, energy_flags: dict, kept: dict) -> dict:
    """User rule 2026-10-10 (C3 control): an energy-flagged +/-Q pair that the curvature rule did not keep is kept PROVISIONALLY
    when its direction also has a +/-2Q pair and no member of either carries a flag but the energy guard's. The collector then
    writes a second coupling set with the +/-2Q derivatives on those directions, and compute_excited_state_spin_relaxation
    accepts the T1 only if it moves < 5% between the two sets. Why the observable and not matrix linearity: on C3 the NEVPT2
    excited-excited block of dirs 31-42 is 4-19% nonlinear (near-crossing excited d levels; CASSCF stays 0.1-0.3% linear) while
    the T1 moves 0.75%. Returns {label: evidence} for the provisionally kept members."""
    pairs = {(p["direction"], p["multiple"]): [by_pair.get((p["pair"], s), "") for s in ("plus", "minus")] for p in manifest["pairs"]}
    out = {}
    for (j, m), labs in pairs.items():
        two = pairs.get((j, 2))
        if m != 1 or not two or not any(lab in energy_flags and lab not in kept for lab in labs):
            continue
        group = labs + two
        if all(lab in points and not flags.get(lab) for lab in group):
            for lab in group:
                if lab in energy_flags and lab not in kept:
                    out[lab] = {"flag": energy_flags[lab], "direction": j, "rule": "provisional: T1 step test (+/-Q vs +/-2Q) in compute_excited_state_spin_relaxation"}
    return out


def add_excited_state_linearity_members(
    sweep_manifest: Annotated[str, "orca_sweep_manifest.json of a Gamma_II sweep."],
    directions: Annotated[str, "Direction indices needing +/-2Q members, e.g. '31 37 40' (collect_excited_state_couplings names them)."],
    runtime: ToolRuntime = None,
) -> Dict[str, Any]:
    """Add +/-2Q members for the named directions to an existing Gamma_II sweep: the +/-Q member's input with twice its
    displacement (same protocol, reference orbitals and embedding file), recorded in the displacement and sweep manifests.
    Then submit_orca_displacement_sweep runs only these pending members; collect_excited_state_couplings keeps the energy-flagged
    pairs provisionally and compute_excited_state_spin_relaxation runs the T1 step test (< 5%)."""
    try:
        import shutil

        from ElAgenteQ.skill_library import orca_sweeps as osw

        root, path, sweep = osw._load_sweep(runtime, sweep_manifest)
        if sweep.get("displacement_kind") != KIND:
            raise ValueError("Not a Gamma_II sweep (prepare_orca_displacement_sweep on an export_excited_state_displacements manifest).")
        man_path = osw._resolve(root, sweep["displacement_manifest"])
        man = json.loads(man_path.read_text())
        jobs = {job["job_label"]: job for job in sweep["jobs"]}
        coord_re = r"(?ims)(^\s*\*\s*xyz\s+\S+\s+\S+\s*$\n)(.*?)(^\s*\*\s*$)"

        def coords(text):
            rows = [line.split() for line in re.search(coord_re, text).group(2).splitlines() if line.strip()]
            return [r[0] for r in rows], np.array([[float(x) for x in r[1:4]] for r in rows])

        symbols, ref_xyz = coords((root / jobs["reference"]["input_path"]).read_text())
        wanted = sorted({int(x) for x in re.split(r"[\s,]+", directions.strip()) if x})
        have2 = {p["direction"] for p in man["pairs"] if p["multiple"] == 2}
        added, skipped = [], []
        for j in wanted:
            if j in have2:
                skipped.append(j)
                continue
            one = next((p for p in man["pairs"] if p["direction"] == j and p["multiple"] == 1), None)
            if one is None:
                raise ValueError(f"direction {j} has no +/-Q pair in {_h._rel(root, man_path)}")
            pair = max(p["pair"] for p in man["pairs"]) + 1
            man["pairs"].append({"pair": pair, "direction": j, "multiple": 2, "q": 2 * one["q"]})
            for sign, tag in ((1, "plus"), (-1, "minus")):
                src = next(m for m in man["members"] if m["pair"] == one["pair"] and m["sign"] == sign)
                src_job = jobs[src["member"]]
                text = (root / src_job["input_path"]).read_text()
                syms, xyz = coords(text)
                if syms != symbols:
                    raise ValueError(f"{src['member']}: atom list differs from the reference input")
                new = ref_xyz + 2 * (xyz - ref_xyz)
                block = "".join(f"  {a:2s} {x:16.10f} {y:16.10f} {z:16.10f}\n" for a, (x, y, z) in zip(symbols, new))
                label = f"dir{j:03d}_x2_{tag}"
                text2 = re.sub(coord_re, lambda m_: m_.group(1) + block + m_.group(3), text, count=1)
                if osw.protocol_sha256(text2) != sweep["protocol_sha256"]:
                    raise ValueError(f"{label}: the protocol changed while writing the input")
                src_dir = (root / src_job["input_path"]).parent
                job_dir = src_dir.parent / label
                job_dir.mkdir(exist_ok=False)
                for dep in src_dir.iterdir():  # reference orbitals and embedding/LJ files, not the member's own outputs
                    if dep.suffix in (".gbw", ".pc", ".lj") and not dep.name.startswith(src["member"]):
                        shutil.copy2(dep, job_dir / dep.name)
                (job_dir / f"{label}.inp").write_text(text2)
                disp = 2 * np.asarray(src["displacement"], dtype=float)
                man["members"].append({"member": label, "pair": pair, "sign": sign, "direction": j, "multiple": 2, "q": 2 * src["q"],
                                       "displacement": np.round(disp, 12).tolist(), "qm_xyz": f"displaced_xyz/{label}.xyz"})
                _write_xyz(man_path.parent / "displaced_xyz" / f"{label}.xyz", symbols, new, f"direction {j} Q = {2 * src['q']:.8f} amu^1/2 A (added)")
                sweep["jobs"].append({**{k: v for k, v in src_job.items() if k not in ("job_label", "input_path", "expected_output_path",
                                                                                    "geometry_sha256", "source_member", "mode_index")},
                                      "job_label": label, "input_path": _h._rel(root, job_dir / f"{label}.inp"),
                                      "expected_output_path": _h._rel(root, job_dir / f"{label}.out"), "source_member": label,
                                      "mode_index": pair, "geometry_sha256": osw.geometry_sha256(text2)})
                added.append(label)
        sweep["job_count"] = len(sweep["jobs"])
        if added and sweep.get("manifest_source"):  # the +/- coverage CSV the submitter checks: one row per pair
            pairs_csv = osw._resolve(root, sweep["manifest_source"])
            text = pairs_csv.read_text()
            with pairs_csv.open("a") as handle:
                if text and not text.endswith("\n"):
                    handle.write("\n")
                for plus, minus in zip(added[0::2], added[1::2]):
                    handle.write(f"{next(j['mode_index'] for j in sweep['jobs'] if j['job_label'] == plus)},{plus},{minus}\n")
        man_path.write_text(json.dumps(man))
        path.write_text(json.dumps(sweep, indent=1))
        return {"ok": True, "added_members": added, "directions_with_existing_2q": skipped, "sweep_manifest": _h._rel(root, path),
                "next_step": "submit_orca_displacement_sweep(sweep_manifest, execution_mode='submit') runs only the pending members; "
                             "then collect_excited_state_couplings."}
    except Exception as exc:
        return _h._error(exc)


def collect_excited_state_couplings(
    sweep_manifest: Annotated[str, "orca_sweep_manifest.json of prepare_orca_displacement_sweep on an export_excited_state_displacements manifest."],
    repeat_outputs: Annotated[str, "Optional: CASSCF outputs of the REFERENCE geometry restarted from other orbitals (space-separated paths): the coupling noise floor."] = "",
    energy_tolerance_eh: Annotated[float, "Flag a member whose CASSCF ground-root energy departs from the sweep's undisplaced member by more than this (Eh); the flag is then adjudicated by LF consistency (kept only if its pair's LF second difference sits inside the clean pairs' range)."] = 0.005,
    runtime: ToolRuntime = None,
) -> Dict[str, Any]:
    """Vibronic couplings of a finished Gamma_II sweep: verifies every member (protocol / geometry / orbital hashes, normal
    termination, CASSCF convergence, the d^n AILFT active space, ORCA version, ground-root energy, d character), re-aligns each
    AILFT ligand-field and SOC matrix onto the ideal d orbitals, differentiates +/-Q pairs (a pair with a flagged member is
    refused), projects onto the Gamma modes, and checks two-step linearity, repeat noise and the libration coupling
    (= -i[J, H]). Writes excited_state_couplings.json for compute_excited_state_spin_relaxation."""
    try:
        from ElAgenteQ.skill_library import orca_sweeps as osw
        from ElAgenteQ.skill_library.campaign_ledger.campaign_ledger import record_validator_receipt
        from ElAgenteQ.skill_library.slurm_interaction.slurm_tools import _orca_output_diagnostics

        root, path, sweep = osw._load_sweep(runtime, sweep_manifest)
        if sweep.get("displacement_kind") != KIND:
            raise ValueError("Not a Gamma_II sweep (prepare_orca_displacement_sweep on an export_excited_state_displacements manifest).")
        man = json.loads(osw._resolve(root, sweep["displacement_manifest"]).read_text())
        d_count = int(man["d_count"])
        ref_out = osw._resolve(root, sweep["reference_gbw"]).with_suffix(".out")
        problems = reference_problems(ref_out, d_count)
        if problems:
            raise ValueError(f"reference {_h._rel(root, ref_out)}: {'; '.join(problems)}")
        reference = realigned_point(ref_out, d_count, need_nevpt2=True)
        integrity = osw._integrity_problems(root, sweep)
        points, flags = {}, {}
        for job in sweep["jobs"]:
            label, out = job["job_label"], root / job["expected_output_path"]
            flags[label] = list(integrity.get(label, []))
            state = _orca_output_diagnostics(out)
            if state["scientific_state"] != "validated":
                flags[label].append(f"not_validated ({state['status']})")
                continue
            try:
                points[label] = realigned_point(out, d_count)
            except (ValueError, StopIteration, IndexError) as exc:
                flags[label].append(f"ailft: {exc}")
        r0, energy_flags = points.get("reference"), {}
        if r0 is None or flags.get("reference"):
            raise ValueError(f"the sweep's undisplaced member is unusable: {flags.get('reference') or 'missing'}")
        for label, p in points.items():
            if p["version"] != r0["version"]:
                flags[label].append(f"orca_version_mismatch ({p['version']} vs {r0['version']})")
            if p["energy_eh"] is not None and abs(p["energy_eh"] - r0["energy_eh"]) > float(energy_tolerance_eh):
                energy_flags[label] = f"energy_vs_reference: {p['energy_eh'] - r0['energy_eh']:+.6f} Eh"
            if p["d_singular_values"].min() < 0.8 * r0["d_singular_values"].min():
                flags[label].append(f"d_character_lost: smallest d-part singular value {p['d_singular_values'].min():.3f} vs {r0['d_singular_values'].min():.3f}")
        by_pair = {(job["mode_index"], job["sign"]): job["job_label"] for job in sweep["jobs"] if "mode_index" in job}
        adjudicated = lf_consistency_adjudication(man, by_pair, points, flags, energy_flags, r0)
        step_kept = step_test_adjudication(man, by_pair, points, flags, energy_flags, adjudicated)
        adjudicated.update(step_kept)
        for label, flag in energy_flags.items():
            if label not in adjudicated:
                flags[label].append(flag)
        fd, refused = {}, {}
        for pr in man["pairs"]:
            labels = [by_pair.get((pr["pair"], s), "") for s in ("plus", "minus")]
            bad = [f"{lab}: {f}" for lab in labels for f in (flags.get(lab) if lab in flags else ["missing"])]
            if bad or not all(lab in points for lab in labels):
                refused[f"direction {pr['direction']} x{pr['multiple']}"] = bad or ["values missing"]
            else:
                fd[(pr["direction"], pr["multiple"])] = (points[labels[0]], points[labels[1]])
        flagged = {label: f for label, f in flags.items() if f}
        if len({k[0] for k in fd if k[1] == 1}) < len(man["directions_mass_weighted"]):
            have2 = {p["direction"] for p in man["pairs"] if p["multiple"] == 2}
            need2 = sorted({p["direction"] for p in man["pairs"] if p["multiple"] == 1 and p["direction"] not in have2
                            and any(by_pair.get((p["pair"], s_), "") in energy_flags for s_ in ("plus", "minus"))})
            hint = ({"next_step": f"energy-flagged pairs on directions {need2} failed the curvature rule: add_excited_state_linearity_members"
                                  f"(sweep_manifest, directions='{' '.join(map(str, need2))}'), submit the pending members, collect again"}
                    if need2 else {})
            return {"ok": False, "error": "directions without a usable +/-Q pair: no couplings written (rerun or fix those members)",
                    "refused_pairs": dict(list(refused.items())[:30]), "flagged_points": dict(list(flagged.items())[:30]), **hint}
        repeats = [realigned_point(osw._resolve(root, p), d_count) for p in repeat_outputs.split()]
        result = couplings_from_points(man, reference, fd, r0, repeats)
        warnings = []
        lin = [r for r in result["checks"]["linearity"] if max(r["rel_diff_V"], r["rel_diff_h"]) > 0.02]
        if lin:
            warnings.append(f"Two-step derivatives differ by > 2% on directions {[r['direction'] for r in lin]}: anharmonic or noisy; check those members.")
        lib = result["checks"]["libration"]
        inside = [r for r in lib if r["span_coverage"] >= 0.99]
        worst = max((r["relative_error"] for r in inside), default=float("nan"))
        if len(inside) < len(lib):
            warnings.append(f"Rigid rotations only {min(r['span_coverage'] for r in lib):.1%} inside the direction span: the libration check is "
                            "inconclusive and librations are under-covered (raise mode_cutoff_cm1 / extension_weight).")
        if inside and worst > 0.1:
            warnings.append(f"Libration coupling off -i[J, H] by up to {worst:.0%} (VOPc, 47 directions: 2-4%): span or re-alignment problem.")
        if refused:
            warnings.append(f"{len(refused)} two-step pairs refused (linearity not checked there).")
        by_curvature = [k for k, v in adjudicated.items() if "rule" not in v]
        if by_curvature:
            warnings.append(f"{len(by_curvature)} members past the energy guard kept: their pairs' LF second differences sit inside the "
                            "clean pairs' range (another inactive-orbital solution, same d manifold); see energy_flags_adjudicated.")
        result.update({"sweep_manifest": _h._rel(root, path), "displacement_manifest": sweep["displacement_manifest"],
                       "reference_output": _h._rel(root, ref_out), "phonon_set_sha256": man.get("phonon_set_sha256"),
                       "flagged_points": flagged, "refused_pairs": refused, "energy_flags_adjudicated": adjudicated, "warnings": warnings})
        step_dirs = sorted({v["direction"] for v in step_kept.values()})
        if step_dirs:
            # the same couplings with the +/-2Q derivatives on the provisionally kept directions (the T1 step test)
            man_alt = {**man, "steps": [{**st, "q": 2 * st["q"]} if st["direction"] in step_dirs else st for st in man["steps"]]}
            fd_alt = {**fd, **{(j, 1): fd[(j, 2)] for j in step_dirs}}
            alt = couplings_from_points(man_alt, reference, fd_alt, r0, repeats)
            alt_file = path.parent / "excited_state_couplings_step2.json"
            alt_file.write_text(json.dumps({**alt, "step_test_alternative_of": "excited_state_couplings.json", "step_test_directions": step_dirs}))
            result["step_test"] = {"directions": step_dirs, "alternative_couplings": alt_file.name, "threshold_relative_T1": 0.05}
            warnings.append(f"Directions {step_dirs} kept provisionally: compute_excited_state_spin_relaxation accepts the T1 only if "
                            "it moves < 5% with their +/-2Q derivatives.")
        saved = path.parent / "excited_state_couplings.json"
        saved.write_text(json.dumps(result))
        receipt = record_validator_receipt(root, validator="excited_state_couplings", passed=not flagged and not refused,
                                           artifacts=[path, saved], summary=f"{len(fd)} pairs differentiated, {len(flagged)} flagged, "
                                                                            f"{len(refused)} refused; libration max error {worst:.3f}")
        brief = {k: v for k, v in result.items() if k not in {"mode_couplings", "mode_couplings_casscf_dV", "direction_couplings", "reference"}}
        brief["modes"] = {"n": len(result["modes"]["frequencies_cm1"]), "coverage_min": round(min(result["modes"]["coverage"]), 4)}
        return {"ok": True, **brief, "saved": _h._rel(root, saved), "validator_receipt": receipt["id"]}
    except Exception as exc:
        return _h._error(exc)


# --------------------------------------------------------------------------- #
# T1
# --------------------------------------------------------------------------- #


def _gamma_i(root, spin_relaxation_json: str, field: float, sigma: float, temps) -> tuple[dict[float, float | None], str]:
    """Gamma_I Raman T1 per temperature from a compute_spin_relaxation_time output on the same footing."""
    path = _h._resolve_path(root, spin_relaxation_json, must_exist=True, dir_ok=False)
    data = json.loads(path.read_text())
    if "results" not in data or "field_tesla" not in data:
        raise ValueError(f"{path.name} is not a compute_spin_relaxation_time output.")
    if abs(float(data["field_tesla"]) - field) > 1e-9 or abs(float(data["broadening_cm1"]) - sigma) > 1e-9:
        raise ValueError(f"Gamma_I was computed at {data['field_tesla']} T, sigma {data['broadening_cm1']} cm-1: pass the same field_tesla / broadening_cm1.")
    if str(data.get("field_direction", "powder")).strip().lower() != "powder":
        raise ValueError("Gamma_I must be a powder average (field_direction='powder'), like Gamma_II.")
    rows = {float(r["T_K"]): r.get("T1_raman_s") for r in data["results"]}
    absent = [t for t in temps if t not in rows]
    if absent:
        raise ValueError(f"Gamma_I has no rows at {absent} K (it has {sorted(rows)}).")
    return rows, _h._rel(root, path)


def compute_excited_state_spin_relaxation(
    couplings_json: Annotated[str, "excited_state_couplings.json of collect_excited_state_couplings."],
    spin_relaxation_json: Annotated[str, "Optional compute_spin_relaxation_time output (powder, same field and sigma): its Raman T1 is Gamma_I, and the total is reported."] = "",
    field_tesla: Annotated[float, "Magnetic field (T): 0.35 X band, 1.2 Q band (Gamma_II is B-independent to ~1e-4)."] = 0.35,
    temperatures_k: Annotated[str, "Temperatures (K); '' = those of spin_relaxation_json, else '5 10 20 50 100 200 300'."] = "",
    broadening_cm1: Annotated[float, "Gaussian standard deviation sigma (cm-1), as in compute_spin_relaxation_time."] = 10.0,
    compound: Annotated[str, "Compound label for the calibration record."] = "",
    covalency_g_target: Annotated[str, COVALENCY_DOC] = "",
    runtime: ToolRuntime = None,
) -> Dict[str, Any]:
    """Gamma_II (excited-state, Mariano/Lunghi 2024; its B-independent part = Shushkov's Berry-curvature term) spin-lattice T1(T)
    of an S = 1/2 d1/d9 ion from collect_excited_state_couplings, powder-averaged, with Gamma_I (Raman of
    compute_spin_relaxation_time) and the total 1/T1 = 1/T1_I + 1/T1_II; T1(B || metal axis) / T1(B perp); the dominant modes,
    mode pairs and excited Kramers doublets; detailed balance, B-independence, curvature-only and CASSCF-level T1. Cu(II): pass
    covalency_g_target (a B3LYP ZORA EPR output of the same molecule; measured g only as a sensitivity) -- the CAS(9,5) SOC is too
    ionic and the uncorrected rate ~1.7x too fast."""
    root = _h._root(runtime)
    try:
        cpath = _h._resolve_path(root, couplings_json, must_exist=True, dir_ok=False)
        data = json.loads(cpath.read_text())
        if data.get("kind") != COUPLINGS_KIND:
            raise ValueError(f"{cpath.name} is not a collect_excited_state_couplings output.")
        d_count, field, sigma = int(data["d_count"]), float(field_tesla), float(broadening_cm1)
        if field <= 0 or sigma <= 0:
            raise ValueError("field_tesla and broadening_cm1 must be > 0.")
        v0, vc, h0 = (np.array(data["reference"][k], dtype=float) for k in ("V_nevpt2", "V_casscf", "h_soc"))
        freqs = np.array(data["modes"]["frequencies_cm1"], dtype=float)
        dv, dh = np.array(data["mode_couplings"]["dV"], dtype=float), np.array(data["mode_couplings"]["dh"], dtype=float)
        h_raw, dh_raw, covalency = h0, dh, None
        if covalency_g_target.strip():  # orbital reduction of every SOC element (h and dh/dQ), fitted to the target g
            g_target, source = target_g(covalency_g_target, root)
            covalency = {"source": source, **fit_orbital_reduction(v0, h0, d_count, g_target, data["reference"].get("orca_g_nevpt2"))}
            if covalency["max_abs_g_residual"] > 1e-4:
                raise ValueError(f"No orbital reduction reproduces g {g_target} (residual {covalency['max_abs_g_residual']:.2g}): check the target.")
            h0, dh = soc_reduced(h0, covalency["kappa_xyz"]), soc_reduced(dh, covalency["kappa_xyz"])
        dops = coupling_operators(dv, dh, d_count)
        gamma_i, gi_path = ({}, None)
        if temperatures_k.strip():
            temps = [float(t) for t in temperatures_k.split()]
        elif spin_relaxation_json.strip():
            temps = [float(r["T_K"]) for r in json.loads(_h._resolve_path(root, spin_relaxation_json, must_exist=True, dir_ok=False).read_text())["results"]]
        else:
            temps = [5.0, 10.0, 20.0, 50.0, 100.0, 200.0, 300.0]
        if not temps or min(temps) <= 0:
            raise ValueError("Every temperature must be > 0.")
        if spin_relaxation_json.strip():
            gamma_i, gi_path = _gamma_i(root, spin_relaxation_json, field, sigma, temps)

        def powder(v=v0, h=h0, ops=dops, f=freqs, b=field, **kw):
            return gamma2_powder(v, h, ops, f, b, temps, sigma, d_count, **kw)

        main = powder()
        rate = main["rate"]
        if covalency is not None:
            uncorrected = powder(h=h_raw, ops=coupling_operators(dv, dh_raw, d_count))["rate"]
            covalency["rate_ratio_corrected_over_uncorrected"] = [round(float(x), 5) for x in rate / uncorrected]
        axis = [gamma2_direction(v0, h0, dops, freqs, field * np.eye(3)[k], temps, sigma, d_count)["rate"] for k in range(3)]
        rate_par, rate_perp = axis[2], (axis[0] + axis[1]) / 2
        curvature = powder(part="curvature")["rate"]
        weak_field = powder(b=field / 10)["rate"]
        level = data.get("couplings_level", "casscf")  # 'nevpt2', 'nevpt2_constshift' or (older files) 'casscf' = mixed
        ops_cas = coupling_operators(np.array(data.get("mode_couplings_casscf_dV", dv), dtype=float), dh, d_count)
        casscf = powder(v=vc, ops=ops_cas)["rate"]  # CASSCF levels and couplings
        mixed = powder(ops=ops_cas)["rate"] if level != "casscf" else rate  # NEVPT2 levels, CASSCF couplings
        top = len(temps) - 1
        # dominant modes and pairs at the highest temperature
        pairs = main["pairs"][top]
        share = (pairs.sum(axis=0) + pairs.sum(axis=1)) / 2 / max(pairs.sum(), 1e-300)
        order = np.dstack(np.unravel_index(np.argsort(-pairs.ravel()), pairs.shape))[0][:8]
        edges = sorted({0.0, 60.0, 150.0, 300.0, float(freqs.max())})
        bands = {f"{lo:g}-{hi:g}": round(float(share[(freqs > lo) & (freqs <= hi)].sum()), 4) for lo, hi in zip(edges[:-1], edges[1:])}
        # excited Kramers doublets: rate with only that doublet as intermediate, and without it
        e0, u0 = np.linalg.eigh(ion_hamiltonian(v0, h0, (0.0, 0.0, 0.0), d_count))
        char = orbital_character(u0)
        doublets = []
        for c in ((2, 3), (4, 5), (6, 7), (8, 9)):
            only = gamma2_powder(v0, h0, dops, freqs, field, [temps[top]], sigma, d_count, cset=c)["rate"][0]
            without = gamma2_powder(v0, h0, dops, freqs, field, [temps[top]], sigma, d_count, cset=[k for k in range(2, 10) if k not in c])["rate"][0]
            w = char[list(c)].mean(axis=0)
            doublets.append({"states": list(c), "energy_cm1": round(float(e0[list(c)].mean() - e0[0]), 1),
                             "character": {D_LABELS[i]: round(float(w[i]), 3) for i in np.argsort(-w)[:2]},
                             "rate_only_this_over_full": round(float(only / rate[top]), 5), "rate_without_this_over_full": round(float(without / rate[top]), 5)})
        # phonon-cutoff convergence
        cutoffs = {}
        for wc in sorted({150.0, round(0.5 * freqs.max()), round(0.75 * freqs.max())}):
            sel = freqs <= wc
            if 2 <= sel.sum() < len(freqs):
                cutoffs[f"{wc:g}"] = [_finite(1 / r) for r in powder(ops=dops[sel], f=freqs[sel])["rate"]]
        g_model = g_tensor(v0, h_raw, d_count)[0]
        g_orca = data["reference"].get("orca_g_nevpt2")
        warnings = list(data.get("warnings", []))
        if d_count == 9 and covalency is None:
            warnings.append("Cu(II) d9 without covalency_g_target: the CAS(9,5) hole is too metal-localised (CuOEP: g-shifts 1.6-1.8x too large "
                            "with correct d-d energies), so Gamma_II is ~1.7x too fast. Pass a B3LYP g of the same molecule as covalency_g_target "
                            "(within 12% of the measured shifts; the general rule for candidates). Use a measured g only as a sensitivity check.")
        phonon_source = data.get("phonon_source")
        if phonon_source and phonon_source.startswith("MLIP"):
            warnings.append(MLIP_PRESCREEN_NOTE)
        low = [round(float(f), 1) for f, cv in zip(freqs, data["modes"]["coverage"]) if cv < 0.9]
        if low:
            warnings.append(f"Modes {low} cm-1 lie < 90% inside the finite-difference span: their couplings are truncated (rate a lower bound).")
        drift = float(np.max(np.abs(weak_field / rate - 1)))
        if drift > 0.01:
            warnings.append(f"Gamma_II changes by up to {drift:.1%} between B and B/10: the field-dependent (Van Vleck) term is not negligible.")
        if g_orca:
            shift_model, shift_orca = np.sort(g_model) - G_E, np.sort(g_orca) - G_E
            if np.any(np.sign(shift_model) != np.sign(shift_orca)) or np.any(np.abs(shift_model) > 2 * np.abs(shift_orca) + 1e-3):
                warnings.append(f"Model g {np.round(g_model, 4).tolist()} vs ORCA NEVPT2 {g_orca}: wrong d count, hole picture or SOC.")
        last = list(cutoffs.values())[-1][top] if cutoffs else None
        if last and abs(last * rate[top] - 1) > 0.1:
            warnings.append(f"T1_II at {temps[top]:g} K changes by {last * rate[top] - 1:+.0%} from modes <= {list(cutoffs)[-1]} cm-1 to all "
                            f"(<= {freqs.max():.0f}): check convergence in mode_cutoff_cm1.")
        t1_ii = [_finite(1 / r) for r in rate]
        results = []
        for k, t in enumerate(temps):
            t1_i = gamma_i.get(t) if gamma_i else None
            total = 1 / (rate[k] + (1 / t1_i if t1_i else 0.0))
            results.append({"T_K": t, "T1_II_s": t1_ii[k], "T1_I_raman_s": t1_i, "T1_total_s": _finite(total),
                            "T1_II_B_par_s": _finite(1 / axis[2][k]), "T1_II_B_perp_s": _finite(1 / rate_perp[k]),
                            "anisotropy_par_over_perp": round(float(rate_perp[k] / rate_par[k]), 4),
                            "T1_II_curvature_only_s": _finite(1 / curvature[k]), "T1_II_casscf_s": _finite(1 / casscf[k]),
                            "T1_II_mixed_scheme_s": _finite(1 / mixed[k]),
                            "field_independence_rate_ratio": round(float(weak_field[k] / rate[k]), 6)})
            if covalency is not None:
                results[-1]["T1_II_uncorrected_s"] = _finite(1 / uncorrected[k])
        tag = f"{_h._safe_path_part(compound, 'run')}_{field:g}T"
        result = {
            "compound": compound, "metal": data.get("metal"), "d_count": d_count, "field_tesla": field, "broadening_cm1": sigma,
            "phonon_source": phonon_source or "DFT phonopy set (no fc_provenance.json)",
            "couplings_level": level,
            "couplings": _h._rel(root, cpath), "gamma_I_source": gi_path, "n_modes": len(freqs), "max_mode_cm1": round(float(freqs.max()), 1),
            "results": results, "detailed_balance_max_relative_error": main["balance"],
            "g_model_k1": np.round(g_model, 5).tolist(), "g_orca_nevpt2": g_orca, "lf_levels_cm1": data.get("lf_levels_cm1"),
            "covalency": covalency,
            f"top_modes_{temps[top]:g}K": [{"mode": (data["modes"].get("indices") or list(range(len(freqs))))[i], "frequency_cm1": round(float(freqs[i]), 2),
                                            "share": round(float(share[i]), 4)} for i in np.argsort(-share)[:8]],
            f"band_shares_{temps[top]:g}K": bands,
            f"top_mode_pairs_{temps[top]:g}K": [{"absorbed_cm1": round(float(freqs[a]), 2), "emitted_cm1": round(float(freqs[b]), 2),
                                                 "share": round(float(pairs[a, b] / max(pairs.sum(), 1e-300)), 4)} for a, b in order],
            f"excited_doublets_{temps[top]:g}K": doublets, "T1_II_vs_mode_cutoff_s": cutoffs,
            "warnings": warnings,
            "calibration_record": {"compound": compound, "metal": data.get("metal"), "T_K": temps, "T1_s": [r["T1_total_s"] for r in results],
                                   "process": ("gamma_I_raman+gamma_II" if gamma_i else "gamma_II")
                                              + (f" (SOC orbital reduction k_par {covalency['k_par']:.3f}, k_perp {covalency['k_perp']:.3f}: {covalency['source']})"
                                                 if covalency else "")},
            "conventions": {
                "gamma_II": "W_b->a = 4 pi^2 c sum_{alpha != beta} |sum_c V^a_ac V^b_cb/(E_c-E_b+w_b) + V^b_ac V^a_cb/(E_c-E_b-w_a)|^2 "
                            "<Q_a^2>_0 <Q_b^2>_0 D n(w_a') (n(w_b')+1); NEVPT2 LF levels, couplings at couplings_level, ab initio SOC "
                            "(times the orbital reduction k_perp, k_perp, k_par per component when 'covalency' is set; else k = 1)",
                "sensitivity": "T1_II_casscf_s: CASSCF levels and couplings; T1_II_mixed_scheme_s: NEVPT2 levels with CASSCF couplings",
                "T1": "1/(W_up + W_down) per direction, 1/T1 averaged over Lebedev-14; total = 1/(1/T1_I_raman + 1/T1_II)",
                "anisotropy": "T1(B || frame z = metal axis) / T1(B perp, rate averaged over x and y)",
                "excited_doublets": "rate with only that Kramers doublet as intermediate / without it, over the full rate (they interfere)",
            },
        }
        step = data.get("step_test")
        if step:
            alt_res = _step_alternative(_h._rel(root, cpath.parent / step["alternative_couplings"]), spin_relaxation_json=spin_relaxation_json,
                                        field_tesla=field_tesla, temperatures_k=temperatures_k, broadening_cm1=broadening_cm1,
                                        compound=f"{compound} [step-test alternative]", covalency_g_target=covalency_g_target, runtime=runtime)
            if not alt_res.get("ok"):
                raise ValueError(f"T1 step test: the +/-2Q coupling set failed: {alt_res.get('error')}")
            rel = {str(r["T_K"]): abs(a["T1_total_s"] / r["T1_total_s"] - 1) for r, a in zip(results, alt_res["results"])
                   if r.get("T1_total_s") and a.get("T1_total_s")}
            worst = max(rel.values(), default=float("inf"))
            result["step_test"] = {"directions": step["directions"], "relative_T1_change": {k: round(v, 5) for k, v in rel.items()},
                                   "max": round(worst, 5), "threshold": step.get("threshold_relative_T1", 0.05)}
            if worst >= float(step.get("threshold_relative_T1", 0.05)):
                return {"ok": False, "error": f"T1 step test FAILED: T1 moves {worst:.1%} when directions {step['directions']} use their "
                        "+/-2Q derivatives (threshold 5%): these couplings are step-dependent; do not use this T1.",
                        "step_test": result["step_test"], "results": results}
        out = cpath.parent / f"excited_state_relaxation_{tag}.json"
        out.write_text(json.dumps(result, indent=1))
        cols = ["T_K", "T1_I_raman_s", "T1_II_s", "T1_total_s", "T1_II_B_par_s", "T1_II_B_perp_s"]
        csv = cpath.parent / f"excited_state_relaxation_{tag}.csv"
        csv.write_text(",".join(cols) + "\n" + "\n".join(",".join("" if r[c] is None else f"{r[c]:.6g}" for c in cols) for r in results) + "\n")
        return {"ok": True, **result, "saved": _h._rel(root, out), "csv": _h._rel(root, csv)}
    except Exception as exc:
        return _h._error(exc)


def _step_alternative(couplings_json: str, **kwargs) -> Dict[str, Any]:
    """The T1 tool on the step-test alternative coupling set (it carries no step_test key, so this does not recurse)."""
    fn = getattr(compute_excited_state_spin_relaxation, "func", compute_excited_state_spin_relaxation)
    return fn(couplings_json, **kwargs)


def _finite(x) -> float | None:
    x = float(x)
    return x if math.isfinite(x) else None


def molecule_gamma_modes_from_hess(
    hess_path: Annotated[str, "ORCA .hess of the relaxed ISOLATED molecule (Opt+Freq; $hessian and $atoms are read)."],
    box_padding_angstrom: Annotated[float, "Vacuum around the molecule in the cubic box written for the cluster carve (A)."] = 15.0,
    output_dir: Annotated[str, "Default: next to the .hess."] = "",
    runtime: ToolRuntime = None,
) -> Dict[str, Any]:
    """Isolated-molecule normal modes for export_excited_state_displacements: writes gamma_modes.json (the mass-weighted internal
    modes, translations/rotations projected out) and molecule_box.extxyz (the same atoms, same order, in a vacuum box). Carve the
    cluster from the box (extract_molecular_cluster_from_crystal, center = the metal; charge_overrides_json for an ion), then
    export_excited_state_displacements(cluster_manifest, phonon_dir='', gamma_modes_json=...). Molecular coupling probes only
    (e.g. a gas-phase mechanism comparison against a reference computed the same way): these are not crystal phonons and give no
    crystal T1."""
    from ase import Atoms
    from ase.io import write

    from ElAgenteQ.skill_library.gas_phase_prescreen import AU_TO_CM1, BOHR_ANGSTROM, internal_normal_modes
    from ElAgenteQ.skill_library.orca_output_parser.orca_property_parsers import _parse_hess_block_matrix

    root = _h._root(runtime)
    try:
        path = _h._resolve_path(root, hess_path, must_exist=True, dir_ok=False)
        lines = path.read_text(errors="ignore").splitlines()
        index = {line.strip(): i for i, line in enumerate(lines) if line.startswith("$")}
        if "$hessian" not in index or "$atoms" not in index:
            raise ValueError(f"{path.name} has no $hessian or $atoms block (an ORCA Freq .hess is needed).")
        at = index["$atoms"]
        atoms = [line.split() for line in lines[at + 2:at + 2 + int(lines[at + 1].split()[0])]]
        symbols = [a[0] for a in atoms]
        masses = np.array([float(a[1]) for a in atoms])
        bohr = np.array([[float(v) for v in a[2:5]] for a in atoms])
        n3 = 3 * len(atoms)
        hess = np.array(_parse_hess_block_matrix(lines, index["$hessian"] + 2, n3, n3)[0])  # Eh/bohr^2
        n_rigid, w, vecs = internal_normal_modes(hess, masses, bohr)
        freqs = np.sign(w) * np.sqrt(np.abs(w)) * AU_TO_CM1
        xyz = bohr * BOHR_ANGSTROM
        side = float((xyz.max(axis=0) - xyz.min(axis=0)).max() + 2 * float(box_padding_angstrom))
        xyz = xyz - (xyz.max(axis=0) + xyz.min(axis=0)) / 2 + side / 2
        out = _h._under_root(root, _h._resolve_path(root, output_dir) if output_dir.strip() else path.parent)
        out.mkdir(parents=True, exist_ok=True)
        write(out / "molecule_box.extxyz", Atoms(symbols, positions=xyz, cell=[side] * 3, pbc=True), format="extxyz")
        modes_file = out / "gamma_modes.json"
        modes_file.write_text(json.dumps({
            "kind": "isolated_molecule_gamma_modes", "source_hess": _h._rel(root, path),
            "source_hess_sha256": hashlib.sha256(path.read_bytes()).hexdigest(), "rigid_modes_projected": n_rigid,
            "force_constants_source": f"isolated-molecule ORCA Hessian ({path.name}); not crystal phonons",
            "frequencies_cm1": freqs.tolist(), "eigenvectors_mass_weighted": vecs.T.tolist(),
            "structure": {"symbols": symbols, "masses": masses.tolist(), "positions_angstrom": xyz.tolist(), "cell": (np.eye(3) * side).tolist()}}))
        imaginary = [round(float(f), 2) for f in freqs if f < 0]
        return {"ok": True, "gamma_modes_json": _h._rel(root, modes_file), "box_structure": _h._rel(root, out / "molecule_box.extxyz"),
                "atoms": len(symbols), "internal_modes": len(freqs), "rigid_modes_projected": n_rigid,
                "lowest_frequencies_cm1": [round(float(f), 2) for f in freqs[:8]], "imaginary_cm1": imaginary,
                **({"warning": "imaginary modes: not a minimum; the export skips them, re-optimise first"} if imaginary else {}),
                "next_step": "extract_molecular_cluster_from_crystal(<box_structure>, center=<metal index>, charge_overrides_json for an ion) "
                             "-> export_excited_state_displacements(cluster_manifest, phonon_dir='', oxidation_state, gamma_modes_json=<this>)"}
    except Exception as exc:
        return {"ok": False, "error": f"{type(exc).__name__}: {exc}"}


excited_state_raman_tool_map = {name: tool(fn) for name, fn in {
    "molecule_gamma_modes_from_hess": molecule_gamma_modes_from_hess,
    "export_excited_state_displacements": export_excited_state_displacements,
    "collect_excited_state_couplings": collect_excited_state_couplings,
    "add_excited_state_linearity_members": add_excited_state_linearity_members,
    "compute_excited_state_spin_relaxation": compute_excited_state_spin_relaxation,
}.items()}
