import ipdb
import numpy as np


class fit:

    """
    Fitting tools for least square fit.
    """

    def trim(data, model_trim):

        """
        Removes data outside of wavelegth range of model grid.

        Parameters
        ----------
        data : 2-D array
            input data in 2-D array of wavelength and flux.
        model_trim : type
            input model in 2-D array of wavelength and flux.

        Returns
        -------
        2-D array
            Trimmed input model in 2-D array of wavelength and flux.

        """
        indexes = np.where(
            np.logical_and(
                model_trim[0] >= np.min(data[0]), model_trim[0] <= np.max(data[0])
            )
        )
        return model_trim[0][indexes], model_trim[1][indexes]

    def find_closest(data_wave, model_wave, model_flux):

        """
        Find model fluxes closest in wavelength to data.

        Parameters
        ----------
        data_wave : 1-D array
            wavelengths of data in microns.
        model_wave : 1-D array
            wavelengths of model in microns.
        model_flux : 1-D array
            scaled flux of model in W M-2

        Returns
        -------
        closest_model_flux: array
            subset of model fluxes

        """
        closest = np.searchsorted(model_wave, data_wave)
        idx = np.clip(closest, 1, len(model_wave) - 1)
        left = model_wave[idx - 1]
        right = model_wave[idx]
        idx -= data_wave - left < right - data_wave
        closest_model_flux = model_flux[idx]
        return closest_model_flux

    def least2_liklihood(_data, _model):
        # least squares fit
        # ipdb.set_trace()
        _stat = np.nansum(np.square(_data - _model) / _model)
        prob = np.exp(-0.5 * np.float128(_stat))
        return prob

    def fit_data(data, model):

        """
        Trims the data, finds the closest match, and returns chi square value.

        Parameters
        ----------
        data : 2D array
            Data with wavelength in microns and flux in W M-2
        model : 2D array
            model with wavelength in microns and scaled flux in W M-2

        Returns
        -------
        stats: float
            chi square value.

        """
        trimmed_model_wave, trimmed_model_flux = fit.trim(data, model)
        matched_model = fit.find_closest(
            data[0], trimmed_model_wave, trimmed_model_flux
        )
        liklihood = fit.least2_liklihood(data[1], matched_model)
        # ipdb.set_trace()
        return liklihood
