import numpy as np
from loguru import logger
from scripts.core.engine.final_tags import GetFinalDf
from scripts.core.data_puller_push.kafka_push import CalculatedDataPush


def ai_modelling(df_train, get_training_inference, df_predicted_tags):
    try:
        get_final_df = GetFinalDf()
        for inv_id in list(df_train.inv_id.unique()):
            for mppt_id in list(df_train.mppt_id.unique()):
                try:
                    model, scaler_x, scaler_y = get_training_inference.data_training(inv_id=inv_id, mppt_id=mppt_id)
                    x_test, y_test, predictions = get_training_inference.data_inference(scaler_x=scaler_x,
                                                                                        scaler_y=scaler_y,
                                                                                        model=model,
                                                                                        inv_id=inv_id,
                                                                                        mppt_id=mppt_id)
                    df_result = get_final_df.get_final_data(x_test=x_test,
                                                            y_test=y_test,
                                                            predictions=predictions)
                    final_dict = get_final_df.get_final_predicted_tags(df_predicted_current_tags=df_predicted_tags,
                                                                       inv_id=inv_id, mppt_id=mppt_id)

                    df_result["timestamp"] = df_result["datetime"].values.astype(np.int64) / 10 ** 9
                    df_result["timestamp"] = df_result["timestamp"].astype('int')
                    df_result['hour'] = df_result['datetime'].dt.hour
                    df_result.loc[df_result['hour'].between(left=18, right=23, inclusive=True),
                                  'predicted_current_mppt'] = 0
                    df_result.loc[df_result['hour'].between(left=0, right=5, inclusive=True),
                                  'predicted_current_mppt'] = 0
                    df_result.drop(['hour'], axis=1, inplace=True)
                    CalculatedDataPush(df_result=df_result, final_tags_dict=final_dict).kafka_data_push()
                    logger.info(f'{final_dict}')
                except Exception as e:
                    logger.exception(f'Exception - {e}')
    except Exception as e:
        logger.exception(f'Exception - {e}')
