import numpy as np
import pandas as pd
import scipy.constants as const

from scipy.optimize import minimize


##########################################################################################
# helper function (Chat GPT)
##########################################################################################

def find_closest_indices(q_list, q_values):
    """
    Find the indices of the closest values in q_list for each value in q_values.

    Parameters:
    q_list (numpy array): Array of values to search in.
    q_values (numpy array): Array of values to find the closest match for.

    Returns:
    numpy array: Indices of the closest values in q_list for each q_value.
    """
    q_list = np.asarray(q_list)  # Ensure q_list is a numpy array
    q_values = np.asarray(q_values)  # Ensure q_values is a numpy array
    
    # Calculate closest indices
    closest_indices = np.abs(q_list[:, None] - q_values).argmin(axis=0)
    return closest_indices


##########################################################################################
# tube parameters
##########################################################################################

def get_radius(m_ind, n_ind, a_CC):
    r = a_CC * np.sqrt(3) / (2*np.pi) * np.sqrt(n_ind**2 + n_ind*m_ind + m_ind**2) # A
    return r

def get_chirality(m_ind, n_ind):
    theta = np.arccos((2*n_ind + m_ind) / (2*np.sqrt(n_ind**2 + n_ind*m_ind + m_ind**2)))
    return theta

def get_k_periodicity(n, m, a_CC):
    gcd1 = np.gcd(2*m+n, 2*n+m)
    t1 = int((2*m+n) / gcd1)
    t2 = -int((2*n+m) / gcd1)
    r1 = m / (m*t1 - n*t2)
    r2 = -n / (m*t1 - n*t2)
    k = 4*np.pi / (3*a_CC) * np.sqrt(r1**2 - r1*r2 + r2**2)
    return k

def get_j_periodicity(n, m):
    gcd1 = np.gcd(2*m+n, 2*n+m)
    t1 = int((2*m+n) / gcd1)
    t2 = -int((2*n+m) / gcd1)

    return m*t1 - n*t2


def sort_subbands(m_ind: int, n_ind: int, energy_threshold = None, dataFrame: bool = False):
    """
    This function takes the chiral indices of a CNT and returns a list of subband indices in ascending energy order (for the conduction band).
    It can also return a pandas-DataFrame with the obtained k- and energy-values at the minimum left and right to k=0. If an energy_threshold (in eV) is specified, then the returned j_list only contains subbands that are (at least partially) below the threshold.
    """

    # parameters 
    gamma0 = 3.033 # eV
    a_CC = 1.42 # A
    tube_radius = get_radius(m_ind, n_ind, a_CC) # A
    chiral_angle = get_chirality(m_ind, n_ind) # rad

    a1 = np.array([np.sqrt(3)/2, 3/2]) * a_CC
    a2 = np.array([-np.sqrt(3)/2, 3/2]) * a_CC
    a1 = rot2D(-chiral_angle, a1)
    a2 = rot2D(-chiral_angle, a2)

    k_period = get_k_periodicity(m_ind, n_ind, a_CC) # 1/A
    j_period = get_j_periodicity(m_ind, n_ind)
    j_list = np.arange(0, j_period, 1, dtype='int')

    # energy minimisation
    energy_func = lambda k, j: band_energy(j, k, 1, tube_radius, gamma0, a1[0], a1[1], a2[0], a2[1])

    x0_list = [-0.2*k_period, 0.2*k_period]
    k_min_energy_list = np.zeros((len(j_list),2))
    e_min_energy_list = np.zeros((len(j_list),2))
    for i_j, j in enumerate(j_list):
        for i_x0, x0 in enumerate(x0_list):
            min_energy = minimize(energy_func, x0=x0, args=(j), method='Nelder-Mead', bounds=[(-k_period/2, k_period/2)], tol=1e-8)
            k_min_energy_list[i_j, i_x0] = min_energy.x[0]
            e_min_energy_list[i_j, i_x0] = energy_func(min_energy.x[0], j)

    # sorting
    sorted_indices = np.argsort(np.min(e_min_energy_list, axis=1))
    e_min_energy_sorted = e_min_energy_list[sorted_indices]
    e_min_energy_sorted_combined = np.min(e_min_energy_sorted, axis=1)
    k_min_energy_sorted = np.array(k_min_energy_list[sorted_indices])
    j_list_sorted = j_list[sorted_indices]

    df_energy = pd.DataFrame({'j': j_list_sorted, 'k left [1/A]': k_min_energy_sorted[:,0], 'k right [1/A]': k_min_energy_sorted[:,1],
                              'e left [eV]': e_min_energy_sorted[:,0], 'e right [eV]': e_min_energy_sorted[:,1], 'e min [eV]': e_min_energy_sorted_combined})

    if energy_threshold is not None:
        j_list_out = j_list_sorted[e_min_energy_sorted_combined < energy_threshold]
    else:
        j_list_out = j_list_sorted

    if dataFrame:
        return j_list_out, df_energy
    else:
        return j_list_out


# 2D vector rotation
def rot2D(theta, vector2D):
    rotMat = np.array([[np.cos(theta), np.sin(theta)], [-np.sin(theta), np.cos(theta)]])
    return np.dot(rotMat, vector2D)

def h12(j, k, tube_radius, gamma0, a11, a12, a21, a22):
    spa1 = j/tube_radius * a11 + k * a12
    spa2 = j/tube_radius * a21 + k * a22
    f = gamma0 * (1 + np.exp(1j * spa1) + np.exp(1j * spa2))
    return f

def band_energy(j, k, sign, tube_radius, gamma0, a11, a12, a21, a22):
    return sign * np.abs(h12(j, k, tube_radius, gamma0, a11, a12, a21, a22))
