import numpy as np
import scipy.constants as const
from scipy.special import kv, iv, gamma
from scipy.special import ive, kve

def get_qt(q, eps):
    """ returns rescaled q according to eps
    q: momentum transfer [1/A]
    eps: relative dielectric constant [1]
    """
    qt = np.sqrt(eps[2]/eps[0]) * np.abs(q)
    return qt

def get_mt(J, eps):
    """ returns rescaled J according to eps
    J: momentum transfer [1]
    eps: relative dielectric constant [1]
    """
    mt = np.sqrt(eps[1]/eps[0]) * np.abs(J)
    return mt

def get_energy(j, k, me, R):
    """
    returns band energy of a 2D electron gas on a cylinder in [eV]
    j: angular quantum number [integer]
    k: wavevector along tube axis [1/A]
    me: effective electron mass [kg]
    R: tube radius [A]
    """
    pref = 1e20 * const.hbar**2/ (2 * me * const.e)
    result = pref * ((j/R)**2 + np.square(k))
    return result

def get_kF(mu, j, me, R):
    """
    returns the Fermi wavevector k corresponding to energy mu in [1/A]
    mu: energy in [eV]
    j: angular quantum number [integer]
    me: effective electron mass [kg]
    R: tube radius [A]
    """
    kF2 = 1e-20 * 2*me * mu*const.e / const.hbar**2 - (j/R)**2
    if kF2 > 0:
        return np.sqrt(kF2)
    else:
        return None
    
def get_jmax(mu, me, R):
    """ 
    returns the highest j-band which is still occupied at k=0
    mu: energy in [eV]
    me: effective electron mass [kg]
    R: tube radius [A]
    """
    energy = mu * const.e # J
    radius = R * 1e-10 # m
    j2 = 2*me*energy * radius**2 / (const.hbar**2)
    jmax = np.floor(np.sqrt(j2))
    return int(jmax)

def dos_cylinder(E_array, me, R):
    """
    Compute density of states g(E) for a 2D electron gas on a cylinder
    E_array : Energies [eV] at which DOS is evaluated
    me : effective mass [kg]
    R : cylinder radius [A]
    Returns DOS per unit length [states/(eV·Å)].
    """
    jmax = get_jmax(np.max(E_array), me, R)
    jlist = np.arange(0, jmax + 1)

    # prefactor derived from dE/dk
    pref = (1 / np.pi) * np.sqrt(me / (2 * (const.hbar ** 2))) * (1e10)  # convert 1/m → 1/Å

    gE = np.zeros_like(E_array)
    for j in jlist:
        # band bottom energy (at k=0)
        E0 = get_energy(j, 0.0, me, R)
        mask = E_array > E0
        gE[mask] += pref / np.sqrt((E_array[mask] - E0) * const.e)

    return gE

def get_Gmq(J, q, rho1, rho2, eps, thresh=3e-3):
    """
    returns the Coulomb Green's function in [(eV A) / (e^2)]

    J: angular quantum number
    q: momentum [1/A]
    rho1, rho2: cylindrical radii [A]
    eps: relative dielectric constant
    thresh: parameter for small q asymptotics
    """

    # Effective parameters
    Jt = get_mt(J, eps)
    qt = np.atleast_1d(get_qt(q, eps))

    rho_min = min(rho1, rho2)
    rho_max = max(rho1, rho2)

    # Physical prefactor
    epsilon0 = const.epsilon_0 / const.e * 1e-10  # e^2 / (eV A)
    pref = 1 / (epsilon0 * eps[0])

    # Arguments
    x_min = qt * rho_min
    x_max = qt * rho_max

    out = np.empty_like(qt, dtype=float)

    # ---- Small-q mask ----
    qt_small = thresh / rho_max
    mask_small = np.abs(qt) < qt_small
    mask_reg = ~mask_small

    # ---- Small-q asymptotics ----
    if np.any(mask_small):
        if Jt == 0:
            gamma_E = np.euler_gamma
            out[mask_small] = -np.log(qt[mask_small] * rho_max / 2.0) - gamma_E
        else:
            out[mask_small] = (1.0 / (2.0 * Jt)) * (rho_min / rho_max) ** Jt

    # ---- Stable evaluation using scaled Bessel functions ----
    if np.any(mask_reg):
        xm = x_min[mask_reg]
        xM = x_max[mask_reg]
        out[mask_reg] = (ive(Jt, xm) * kve(Jt, xM) * np.exp(xm - xM))

    return pref * out


def get_chi_j(mu, j, J, q, o, broad, me, R, mesh=False):
    """ 
    returns the complex charge response function in [e^2/(eV*A)]
    mu: chemical potential
    j: band index
    J: angular number change, i.e. j' = j + J
    q: momentum transfer [1/A] (unscaled by eps)
    o: energy transfer [eV]
    broad: broadening [eV]
    me: effective electron mass [kg]
    R: tube radius [A]
    for mesh=False: returns an array with shape (num_o, num_q)
    for mesh=False: q and o must be 1D arrays with the same length, returns a 1D array
    """
    q_arr = np.atleast_1d(q)
    o_arr = np.atleast_1d(o)

    if mesh:
        # omega should be the first axis, q the second
        o_col = o_arr[:, None]     # shape (num_o,1)
        q_row = q_arr[None, :]     # shape (1,num_q)
    else:
        # element-wise arrays of same length
        o_col = o_arr              # shape (N,)
        q_row = q_arr              # shape (N,)
        # assert len(q_arr) == len(o_arr), 'q-list and o-list have different length'

    kF1 = get_kF(mu, j, me, R) # 1/A
    kF2 = get_kF(mu, j+J, me, R) # 1/A

    pref1 = me / (2 * np.pi * const.hbar**2 * q_row*1e10)         # [e^2/(J*m)]
    pref1 = pref1 * (const.e * 1e-10)                             # [e^2/(eV*A)]
    pref2 = const.hbar**2 / me / const.e * 1e20                   # [eV*A^2]

    d = pref2/2 * ((2*j*J + J**2) / R**2 + q_row**2) - o_col      # [eV]

    lo1 = -pref2 * q_row * kF1
    up1 = pref2 * q_row * kF1
    log1 = np.log(np.abs((broad**2 + (up1 + d)**2) / (broad**2 + (lo1 + d)**2)))
    if broad == 0: res1 = 0
    else: res1 = np.arctan((up1 + d) / broad) - np.arctan((lo1 + d) / broad)

    if kF2 is None:
        log2 = 0
        res2 = 0
    else:
        lo2 = pref2 * q_row * (-kF2 - q_row)
        up2 = pref2 * q_row * (kF2 - q_row)
        log2 = np.log(np.abs((broad**2 + (up2 + d)**2) / (broad**2 + (lo2 + d)**2)))
        if broad == 0: res2 = 0
        else: res2 = np.arctan((up2 + d) / broad) - np.arctan((lo2 + d) / broad)

    # print(f'1DEG: pref', pref1)

    chi = pref1 * ((log2 - log1) + 1j * (res2 - res1))
    return chi # [e^2/(eV*A)]
    # return np.ones_like(q) 

def get_dchidv(mu, J, q, broad, me, R):
    """ 
    returns the derivative of the complex density response function w.r.t. velocity in [e^2/(eV^2 A^2)]
    mu: chemical potential
    J: angular number change, i.e. j' = j + J
    q: momentum transfer [1/A] (scalar or 1D array)
    o: energy transfer [eV] (scalar or 1D array)
    broad: broadening [eV]
    me: effective electron mass [kg]
    R: tube radius [A]
    q and o must be 1D arrays with the same length, returns a 1D array
    """
    jmax = get_jmax(mu, me, R)

    dchidv = np.zeros(len(q), dtype='complex')
    for j in range(0, jmax+1):
        kF1 = get_kF(mu, j, me, R) # 1/A
        kF2 = get_kF(mu, j+J, me, R) # 1/A

        pref1 = me / (2 * np.pi * const.hbar**2 * (q * 1e10))    # [e^2/(J*m)]
        pref1 = pref1 * (const.e * 1e-10)                           # [e^2/(eV*A)]
        pref1 = pref1 * q / broad                                   # [e^2/(eV^2 A^2)]

        pref2 = const.hbar**2 / me / const.e * 1e20                 # [eV*A^2]
        d = pref2/2 * ((2*j*J + J**2) / R**2 + q**2)                # [eV]

        d1lo = -pref2 * q * kF1 + d
        d1up = pref2 * q * kF1 + d
        res1_im = -1 / (1 + (d1up/broad)**2) + 1 / (1 + (d1lo/broad)**2)
        res1_re = -2 * (d1up/broad) / (1 + (d1up/broad)**2) + 2 * (d1lo/broad) / (1 + (d1lo/broad)**2)
        if kF2 is None:
            res2_im = 0
            res2_re = 0
        else:
            d2lo = pref2 * q * (-kF2 - q) + d
            d2up = pref2 * q * (kF2 - q) + d
            res2_im = -1 / (1 + (d2up/broad)**2) + 1 / (1 + (d2lo/broad)**2)
            res2_re = -2 * (d2up/broad) / (1 + (d2up/broad)**2) + 2 * (d2lo/broad) / (1 + (d2lo/broad)**2)

        dchidv += pref1 * ((res2_re - res1_re) + 1j * (res2_im - res1_im))
    return dchidv # [e^2/(eV^2 A^2)]

def get_chi_1DEG(mu, J, q, o, broad, me, R, mesh=False):
    """ 
    returns the charge response function of a 1D electron gas on a cylinder
    mu: chemical potential [eV]
    J: angular number change, i.e. j' = j + J
    q: momentum transfer [1/A] (unscaled by eps)
    o: energy transfer [eV] (scalar or 1D array)
    broad: broadening [eV]
    me: effective electron mass [kg]
    R: tube radius [A]
    returns: array with shape (num_o, num_q) when mesh=False, or 1D array when mesh=False
    """

    jmax = get_jmax(mu, me, R)

    if mesh:
        num_o, num_q = len(o), len(q)
        chi_result = np.zeros((num_o, num_q), dtype='complex')
    else:
        # assert len(q) == len(o), 'q-list and o-list have different length'
        chi_result = np.zeros(len(q), dtype='complex')

    for j in range(0, jmax+1):
        chi_j = get_chi_j(mu, j, J, q, o, broad, me, R, mesh)
        chi_result = chi_result + chi_j
    return chi_result # [e^2/(eV*A)]

def renormalize_chi(chi, J, q, R, eps_l):
    """ 
    returns the renormalised charge density response function in [e^2/(eV*A)]
    chi: bare density response function
    J: angular number change, i.e. j' = j + J (unscaled by eps)
    q: momentum transfer [1/A] (unscaled by eps)
    R: tube radius [A]
    eps_l: relative dielectric constant of the liquid [1]
    returns: array with shape (num_o, num_q) when chi is mesh output
    """
    q_arr = np.atleast_1d(q)

    if chi.ndim == 2:
        # chi has shape (num_o, num_q). Build G_mq with shape (1, num_q) to broadcast over omega
        q_row = q_arr[None, :]          # shape (1,num_q)
        g_mq = get_Gmq(J, q_row, R, R, eps_l)
    else:
        # 1D case: elementwise
        q_vec = q_arr
        g_mq = get_Gmq(J, q_vec, R, R, eps_l)

    chi_RPA = chi / (1 - g_mq * chi)
    return chi_RPA # [e^2/(eV*A)]

def get_ge(chi, J, q, R, eps_l):
    """ 
    returns the bare tubular response function [dimensionless]
    chi: bare density response function [e^2/(eV*A)]
    J: angular number change, i.e. j' = j + J (unscaled by eps)
    q: momentum transfer [1/A] (unscaled by eps)
    R: tube radius [A]
    eps_l: relative dielectric constant of the liquid [1]
    """
    q_arr = np.atleast_1d(q).astype(float)
    if chi.ndim == 2:
        q_row = q_arr[None, :]          # shape (1,num_q)
        G_mq = get_Gmq(J, q_row, R, R, eps_l) # (eV A) / (e^2)
    else:
        G_mq = get_Gmq(J, q_arr, R, R, eps_l)
    return -chi * G_mq

def get_ge_RPA(chi, J, q, R, eps_l):
    """ 
    returns the RPA-renormalized tubular response function
    chi: bare density response function
    J: angular number change, i.e. j' = j + J (unscaled by eps)
    q: momentum transfer [1/A] (unscaled by eps)
    R: tube radius [A]
    eps_l: relative dielectric constant of the liquid [1]
    """
    g0 = get_ge(chi, J, q, R, eps_l)
    g_RPA = g0 / (1 + g0)
    return g_RPA