"""Standalone Gamma_II spin-lattice relaxation core, extracted verbatim from the El Agente repository.

Commit: 91594fcc44c90d2cde013c743d8a60d7794e4f45
Extraction: build_standalone_core.py (AST source segments of the named top-level functions and constants, in source order).
The only textual change is that the module prefixes `sr.` (spin_relaxation) and `cp.` (crystal_phonons) were dropped,
because all extracted names live in this one module. Function bodies are otherwise byte-identical to the commit.
Source files (sha256 of the whole file at the commit) and the names taken from each:
  crystal_phonons.py  sha256 0963856ca5a5b5037d63eef7efd9bf92dd645359a495890c45d29afc5e396c02  -> C_CM_PER_S, mode_mean_square_q
  low_mode_hessian.py  sha256 2a4c8c671f1b9239b84d62406f9d45f642e241986ab204c8c8800966df1dc2e8  -> translations
  spin_relaxation.py  sha256 16be4604e89e16296f715d30ff62f3eb23c563aaa90b71d7c9b010d884b68962  -> MU_B_CM1_PER_T, HC_OVER_K_CM_K, lebedev14, bose, zero_point_q2
  excited_state_raman.py  sha256 46494387cff75eed1ecd623c66f7f65de2a936129157ea8f9b6eb35569f20cd8  -> D_LABELS, EH_TO_CM1, G_E, MU_B, PRE, l_matrices, L_ORB, S_SPIN, L_FULL, S_FULL, J_FULL, zeta_soc, one_electron, ion, ion_hamiltonian, coupling_operators, g_tensor, orbital_character, _gauss, spin_flip_rates, gamma2_direction, gamma2_powder
Dependencies: Python >= 3.10, numpy.
"""
from __future__ import annotations

import itertools
import math
from typing import Any

import numpy as np

# ---- from Hypothesis_generation/skill_library/periodic_dft/crystal_phonons.py ----
C_CM_PER_S = 2.99792458e10
def mode_mean_square_q(freq_cm1: float, temperature_k: float) -> float:
    """<Q^2>_T in amu*A^2 for a harmonic mode (quantum): hbar/(2 w) coth(hbar w / 2kT)."""
    hbar = 1.054571817e-34
    kb = 1.380649e-23
    amu_a2 = 1.66053906660e-27 * 1e-20
    omega = 2 * math.pi * 2.99792458e10 * abs(freq_cm1)
    if omega == 0:
        return float("inf")
    x = hbar * omega / (2 * kb * temperature_k) if temperature_k > 0 else float("inf")
    coth = 1.0 if x > 50 else 1.0 / math.tanh(x)
    return hbar / (2 * omega) * coth / amu_a2


# ---- from Hypothesis_generation/skill_library/periodic_dft/low_mode_hessian.py ----
def translations(masses) -> np.ndarray:
    """(3n, 3) orthonormal rigid translations in mass-weighted coordinates."""
    m = np.asarray(masses, dtype=float)
    t = np.zeros((3 * len(m), 3))
    for a in range(3):
        t[a::3, a] = np.sqrt(m / m.sum())
    return t


# ---- from Hypothesis_generation/skill_library/periodic_dft/spin_relaxation.py ----
MU_B_CM1_PER_T = 0.46686447783
HC_OVER_K_CM_K = 1.438776877
def lebedev14() -> tuple[np.ndarray, np.ndarray]:
    """Lebedev 14-point sphere grid: 6 octahedral (weight 1/15) + 8 cubic (3/40) unit vectors; weights sum to 1."""
    cube = np.array(list(itertools.product((1.0, -1.0), repeat=3))) / np.sqrt(3.0)
    return np.vstack([np.eye(3), -np.eye(3), cube]), np.array([1 / 15] * 6 + [3 / 40] * 8)

def bose(w_cm1, t_k):
    """Bose-Einstein occupation n(w) at T (w > 0 in cm-1)."""
    return 1.0 / np.expm1(np.minimum(HC_OVER_K_CM_K * np.asarray(w_cm1, dtype=float) / max(float(t_k), 1e-12), 700.0))

def zero_point_q2(freqs_cm1) -> np.ndarray:
    """<Q^2>_0 = hbar/(2 w) in amu A^2 (mode_mean_square_q at T = 0)."""
    return np.array([mode_mean_square_q(float(f), 0.0) for f in np.atleast_1d(freqs_cm1)])


# ---- from Hypothesis_generation/skill_library/periodic_dft/excited_state_raman.py ----
D_LABELS = ("dz2", "dxz", "dyz", "dx2-y2", "dxy")
EH_TO_CM1 = 219474.6313705
G_E = 2.00231930436
MU_B = MU_B_CM1_PER_T
PRE = 4 * math.pi**2 * C_CM_PER_S
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 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

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 = 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) * bose(wa, t) * (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(-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 = 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}

