import numpy as np
from scipy.stats import linregress

from nmreval.data import Points
from nmreval.fit.minimizer import FitRoutine
from nmreval.fit.result import FitResult
from nmreval.lib.utils import ArrayLike
from nmreval.models import Arrhenius
from nmreval.utils import kB


def tau_hodge(tg: ArrayLike, rate: ArrayLike) -> (Points, FitResult):
    rate = np.asanyarray(rate)
    tg = np.asanyarray(tg)
    fitter = FitRoutine()
    fitter.set_model(Arrhenius)
    d = fitter.add_data(1000/tg, rate, we='y')

    init = linregress(1000/tg, np.log(rate))

    d.set_parameter([np.exp(init.intercept), 1000*init.slope*kB], fun_kwargs={'invt': 'invt1000'})

    res = fitter.run()[0]
    de = res.parameter['E_{A}']
    tau = kB*tg**2/np.abs(de.value)/rate*60

    return Points(x=1000/tg, y=tau, y_err=tau*de.error/np.abs(de.value), name='Hodge'), res
