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

from ElectronGasCylinderModule import get_chi_1DEG, get_ge, get_ge_RPA, get_Gmq, get_qt, get_mt

# def W_in(rho, R, J, q, eps, thresh=1e-4):
#     """returns W_in(rho) = I_mt(qt * rho) / I_mt(qt * R)
#     rho: inner radius [A]
#     R:   outer radius [A]
#     J: unscaled angular momentum
#     q: unscaled momentum [1/A]
#     eps: relative dielectric constant
#     thresh: parameter for asymptotic expansions (smaller -> more accurate) 
#     """
#     Jt = get_mt(J, eps)
#     qt = get_qt(q, eps)
#     qt = np.atleast_1d(qt)

#     out = np.zeros_like(qt)
    
#     qt_small = thresh / R
#     qt_large = 0.05/thresh / rho
    
#     # Masks for each regime
#     mask_small = np.abs(qt) < qt_small
#     mask_large = np.abs(qt) > qt_large
#     mask_mid = ~(mask_small | mask_large)
    
#     # Expression for each regime
#     out[mask_small] = (rho/R)**Jt
#     out[mask_mid] = iv(Jt, qt[mask_mid] * rho) / iv(Jt, qt[mask_mid] * R)
#     out[mask_large] = np.sqrt(R/rho) * np.exp(qt[mask_large] * (rho-R))
    
#     return out

def W_in(rho, R, J, q, eps, thresh=1e-4):
    """returns W_in(rho) = I_mt(qt * rho) / I_mt(qt * R)
    rho: inner radius [A]
    R:   outer radius [A]
    J: unscaled angular momentum
    q: unscaled momentum [1/A]
    eps: relative dielectric constant
    thresh: parameter for asymptotic expansions (smaller -> more accurate) 
    """
    Jt = get_mt(J, eps)
    qt = get_qt(q, eps)
    qt = np.atleast_1d(qt)

    out = ive(Jt, qt*rho) / ive(Jt, qt*R) * np.exp(-np.abs(qt)*(R-rho))    
    return out

def W_out(rho, R, J, q, eps, thresh=1e-4):
    """ W_out(rho) = K_mt(qt * rho) / K_mt(qt * R)
    rho: outer radius [A]
    R:   inner radius [A]
    J: unscaled angular momentum
    q: unscaled momentum [1/A]
    eps: relative dielectric constant
    thresh: parameter for asymptotic expansions (smaller -> more accurate)
    """
    Jt = get_mt(J, eps)
    qt = get_qt(q, eps)
    qt = np.atleast_1d(qt)

    out = np.zeros_like(qt)
    
    qt_small = thresh / rho
    qt_large = 1/thresh / R
    
    # Masks for each regime
    mask_small = np.abs(qt) < qt_small
    mask_large = np.abs(qt) > qt_large
    mask_mid = ~(mask_small | mask_large)
    
    # Expression for each regime
    if Jt == 0:
        out[mask_small] = np.log(qt[mask_small] * rho) / np.log(qt[mask_small] * R)
    else:
        out[mask_small] = (R/rho)**Jt
    
    out[mask_mid] = kv(Jt, qt[mask_mid] * rho) / kv(Jt, qt[mask_mid] * R)
    out[mask_large] = np.sqrt(R/rho) * np.exp(-qt[mask_large] * (rho-R))
    
    return out

def W_in_p(J, q, R, eps, thresh=1e-4):
    """
    W_in'(rho) = qt * [ I_{mt+1}(qt rho) + I_{mt-1}(qt rho) ] / (2 * I_mt(qt R))
    J: unscaled angular momentum
    q: unscaled momentum [1/A]
    R: tube radius [A]
    eps: relative dielectric constant
    thresh: parameter for asymptotic expansions (smaller -> more accurate) 
    """
    Jt = get_mt(J, eps)
    qt = get_qt(q, eps)
    qt = np.asarray(qt, dtype=float)

    out = np.zeros_like(qt)
    
    qt_small = thresh / R
    qt_large = 1/thresh / R
    
    # Masks for each regime
    mask_small = np.abs(qt) < qt_small
    mask_large = np.abs(qt) > qt_large
    mask_mid = ~(mask_small | mask_large)
    
    # Expression for each regime
    if Jt == 0:
        out[mask_small] = np.square(qt[mask_small]) * R / 2
    else:
        out[mask_small] = 1 / (gamma(Jt) * gamma(Jt+1) * R)

    out[mask_mid] = qt[mask_mid] * (iv(Jt + 1, qt[mask_mid] * R) + iv(Jt - 1, qt[mask_mid] * R)) / (2.0 * iv(Jt, qt[mask_mid] * R))
    out[mask_large] = qt[mask_large]
    
    return out

def W_out_p(J, q, R, eps, thresh=1e-4):
    """
    W_out'(rho) = - qt * [ K_{mt+1}(qt rho) + K_{mt-1}(qt rho) ] / (2 * K_mt(qt R))
    J: unscaled angular momentum
    q: unscaled momentum [1/A]
    R: tube radius [A]
    eps: relative dielectric constant
    thresh: parameter for asymptotic expansions (smaller -> more accurate)
    """
    Jt = get_mt(J, eps)
    qt = get_qt(q, eps)
    qt = np.asarray(qt, dtype=float)

    out = np.zeros_like(qt)
    
    qt_small = thresh / R
    qt_large = 1/thresh / R
    
    # Masks for each regime
    mask_small = np.abs(qt) < qt_small
    mask_large = np.abs(qt) > qt_large
    mask_mid = ~(mask_small | mask_large)
    
    # Expression for each regime
    if Jt == 0:
        out[mask_small] = 1 / (np.log(qt[mask_small] * R) * R)
    else:
        out[mask_small] = -gamma(Jt+1) / (gamma(Jt) * R)

    out[mask_mid] = -qt[mask_mid] * (kv(Jt + 1, qt[mask_mid] * R) + kv(Jt - 1, qt[mask_mid] * R)) / (2.0 * kv(Jt, qt[mask_mid] * R))
    out[mask_large] = -qt[mask_large]
    
    return out

def get_gs_diel(J, q, eps_l, eps_s, R, thresh=1e-2):
    """returns surface response function of the solid (i.e. outside) dielectric medium
    J: unscaled Bessel-m
    q: unscaled momentum [1/A]
    eps_l: relative dielectric constant of the liquid
    eps_s: relative dielectric constant of the solid
    thresh: threshold value for using the asymptotic behaviour of the Bessel functions
    """
    eps_r_l = eps_l[0]
    eps_r_s = eps_s[0]

    Wl_outp_R = W_out_p(J, q, R, eps_l, thresh)
    Ws_outp_R = W_out_p(J, q, R, eps_s, thresh)
    Wl_inp_R  = W_in_p(J, q, R, eps_l, thresh)
    
    num = (eps_r_s * Ws_outp_R - eps_r_l * Wl_outp_R)
    den = (eps_r_l * Wl_inp_R - eps_r_s * Ws_outp_R)

    return -num / den

def get_gl_diel(J, q, eps_l, eps_s, R, thresh=1e-2):
    """returns surface response function of the liquid (i.e. inside) dielectric medium
    J: unscaled Bessel-m
    q: unscaled momentum [1/A]
    eps_l: relative dielectric constant of the liquid
    eps_s: relative dielectric constant of the solid
    thresh: threshold value for using the asymptotic behaviour of the Bessel functions
    """
    eps_r_l = eps_l[0]
    eps_r_s = eps_s[0]

    Ws_outp_R = W_out_p(J, q, R, eps_s, thresh)
    Wl_inp_R  = W_in_p(J, q, R, eps_l, thresh)
    Ws_inp_R  = W_in_p(J, q, R, eps_s, thresh)

    num = (eps_r_s * Ws_inp_R - eps_r_l * Wl_inp_R)
    den = (eps_r_l * Wl_inp_R - eps_r_s * Ws_outp_R)

    return -num / den


def get_phi_ext_q(rho, q, eps0, eps_l):
    """returns the external potential (in Fourier-space) at radius rho for a unit charge at the tube center in eV A / e^2
    rho: radius of external potential (normally R) [A]
    q: unscaled momentum  [1/A]
    eps0: vacuum dielectric constant [e^2/(eV A)]
    eps_l: relative dielectric constant of the liquid
    """
    qt = get_qt(q, eps_l)
    pref = 1/(eps0 * eps_l[0])
    bessel = kv(0, qt*rho)
    return pref * bessel # eV A / e^2

def get_phi_ext_z(rho, z, eps0, eps_l, q_list):
    """returns the external potential in real space at radius rho and axial position z in eV/e^2
    rho: radius of external potential (normally R) [A]
    z: axial position [A]
    eps0: vacuum dielectric constant [e^2/(eV A)]
    eps_l: relative dielectric constant of the liquid
    q_list: q in 1/A for trapezoid integration
    """
    z = np.atleast_1d(z)
    
    pref = 1/(2*np.pi)**2
    phi_ext_z = np.zeros_like(z, dtype=float)
    for iz, z_val in enumerate(z):
        phi_ext_integrand = get_phi_ext_q(rho, q_list, eps0, eps_l) * 2*np.cos(q_list * z_val)
        phi_ext_z[iz] = np.trapezoid(phi_ext_integrand, q_list)
    
    return pref * phi_ext_z.squeeze()

def get_phi_ind_z(gs_list, q_list, rho, z, eps0, eps_l, R):
    """returns the induced potential at radius rho and axial position z in eV/e^2
    gs_list: surface response function [1]
    q_list: unscaled momentum [1/A]
    rho: radius of external potential (normally R) [A]
    z: axial position [A]
    eps0: vacuum dielectric constant [e^2/(eV A)]
    eps_r_l: relative radial dielectric constant of the liquid
    """
    phi_ext_wall = get_phi_ext_q(R, q_list, eps0, eps_l)
    phi_ind_wall = -phi_ext_wall * np.real(gs_list)
    phi_ind_l_q = phi_ind_wall * W_in(rho, R, 0, q_list, eps_l)

    z = np.atleast_1d(z)
    pref = 1/(2*np.pi)**2
    phi_ind_z = np.zeros_like(z, dtype=float)
    for iz, z_val in enumerate(z):
        phi_ind_integrand = phi_ind_l_q * 2*np.cos(q_list * z_val)
        phi_ind_z[iz] = np.trapezoid(phi_ind_integrand, q_list)
    
    return pref * phi_ind_z


def get_chi_Lutt(q, o, eps_l, broad, R, vF, CNT, mesh=False):
    """ returns the Luttinger density response function in [e^2/(eV A)]
    q: unscaled momentum transfer [1/A]
    o: frequency [eV]
    eps_l: relative dielectric constant of the liquid
    broad: broadening [eV]
    vF: Fermi velocity [eV A]
    CNT: if true, account for valley-degeneracy, else only spin-degeneracy
    mesh: (o,q) mesh for 2D plots
    """
    q_arr = np.atleast_1d(q)
    o_arr = np.atleast_1d(o)
    if mesh:
        o = o_arr[:, None]      # shape (num_o,1)
        q = q_arr[None, :]      # shape (1,num_q)
    else:
        o = o_arr               # shape (N,)
        q = q_arr               # shape (N,)

    Vq_list = get_Gmq(0, q, R, R, eps_l) # eV A
    
    if CNT:
        pref = 4 * vF / np.pi
        vc_list = vF * np.sqrt(1 + 4*Vq_list / (np.pi * vF))
    else:
        pref = 2 * vF / np.pi
        vc_list = vF * np.sqrt(1 + 2*Vq_list / (np.pi * vF))

    if (broad == 0 and o == 0):
        chi_val = -pref / vc_list**2
        chi = chi_val * np.ones_like(q)
        return chi
    else:
        chi = pref * np.square(q) / (np.square(o + 1j*broad) - vc_list**2 * np.square(q))
        return chi

def get_chi_2DEG_static_Re(q, mu, me):
    """returns the real part of the static bare density response function of a 2D electron gas (plane geometry)
    in [e^2/(eV*A^2)]
    q: unscaled momentum transfer [1/A]
    mu: Fermi level [eV]
    me: effective electron mass [kg]
    """
    q = np.atleast_1d(q)
    
    kF = np.sqrt(2*me * mu * const.e) / const.hbar * 1e10 # 1/A
    pref = -me / (np.pi * const.hbar**2)                # e^2 kg/(J s)^2 = e^2/(J m^2)
    pref = pref * (const.e * 1e-20)                     # e^2/(eV A^2)

    mask_small = (q <= 2*kF)
    mask_large = ~mask_small

    chi_re = np.zeros(len(q))
    chi_re[mask_small] = pref
    chi_re[mask_large] = pref * (1 - np.sqrt(1 - np.square(2*kF/q[mask_large])))

    return chi_re

def get_chi_2DEG_rolled(q, mu, me, R):
    """returns the real part of the static bare density response function of a 2D electron gas rolled onto a cylinder
    in [e^2/(eV*A)]
    q: unscaled momentum transfer [1/A]
    mu: Fermi level [eV]
    me: effective electron mass [kg]
    R: tube radius [A]
    """
    chi2D = get_chi_2DEG_static_Re(q, mu, me)
    return 2*np.pi*R * chi2D

def get_chi_CNT(q, o, vF, broad, mesh=False):
    """ returns the bare density response function of graphene in [e^2/(eV A)]
    q: unscaled momentum transfer [1/A]
    o: frequency [eV]
    vF: Fermi velocity [eV A]
    broad: broadening [eV]
    mesh: (o,q) mesh for 2D plots
    """
    q_arr = np.atleast_1d(q)
    o_arr = np.atleast_1d(o)
    if mesh:
        o = o_arr[:, None]     # shape (num_o,1)
        q = q_arr[None, :]     # shape (1,num_q)
    else:
        o = o_arr              # shape (N,)
        q = q_arr              # shape (N,)
    
    pref = 2 / np.pi
    if (broad == 0 and o == 0):
        chi = -pref * 2/vF * np.ones(len(q))
    else:
        chi = pref * (q / (o - vF * q + 1j*broad) - q / (o + vF * q + 1j*broad))
    return chi


def get_chi_graph_stat(q, kF, vF):
    """returns the static bare density response function of graphene (plane geometry) in [e^2/(eV*A^2)]
    q: momentum transfer [1/A]
    kF: Fermi wavevector [1/A]
    vF: Fermi velocity [eV A] such that E = vF * k
    """
    q = np.atleast_1d(q)

    pref = -2 * kF / (np.pi * vF)            # e^2/(eV A^2)
    # print(f'DOS = {pref:.1e} e^2/(eV A^2)')

    mask_small = (q <= 2*kF)
    mask_large = ~mask_small

    # Pi+
    chi_re_p = np.zeros(len(q))
    chi_re_p[mask_small] = 1 - np.pi * q[mask_small] / (8 * kF)
    chi_re_p[mask_large] = 1 - 0.5*np.sqrt(1 - 4*kF**2 / np.square(q[mask_large])) - q[mask_large]/(4*kF) * np.arcsin(2*kF/q[mask_large])
    # Pi-
    chi_re_m = np.pi * q / (8*kF)
    # total
    chi_re = chi_re_p + chi_re_m
    return pref * chi_re

def get_chi_graph_rolled(q, kF, vF, R):
    """returns the static bare density response function of graphene in the rolled geometry in [e^2/(eV*A)]
    q: momentum transfer [1/A]
    kF: Fermi wavevector [1/A]
    vF: Fermi velocity [eV A] such that E = vF * k
    R: tube radius [A]
    """
    chi2D = get_chi_graph_stat(q, kF, vF)
    return chi2D * 2*np.pi*R

