if __name__ == "__main__":
    from dotenv import load_dotenv
    load_dotenv(dotenv_path='config.env')
import pandas as pd
import numpy as np
import warnings
from loguru import logger
from scripts.utils.pycaret_util import PycaretUtil
from scripts.core.engine.mppt_data import GetData
from scripts.utils.reading_tags import GetTags
from scripts.core.engine.tags_data import get_tags_data
from scripts.utils.start_end_date import KairosStartEndDate
from scripts.utils.preprocessing import DataPreprocessing
from scripts.core.engine.inv_and_mppt_level import TrainingInference
warnings.filterwarnings("ignore")


base_path = 'data_folder'
start_date, end_date, start_timestamp, end_timestamp = KairosStartEndDate().start_end_date()


def get_tag_details():
    try:
        get_tags = GetTags(base_path=base_path)
        tags_excel = get_tags.read_tag_excel()
        mppt_tags = get_tags.get_mppt_tags(df=tags_excel, substrings='MPPT')
        df = get_tags_data(mppt_tags=mppt_tags,
                           start_timestamp=start_timestamp,
                           end_timestamp=end_timestamp)

        logger.info(f'Shape of final df - {df.shape}')

        mppt_data = GetData()
        df_mppt = mppt_data.current_voltage_mppt_data(df=df)

        data_preprocessing = DataPreprocessing()
        df_mppt = data_preprocessing.remove_outliers(df=df_mppt, param_list=['tilt_irradiance', 'voltage_mppt', 'current_mppt'])
        df_mppt, df_train, df_test = data_preprocessing.train_test_split(df=df_mppt)
        unique_inv_id = list(df_train.inv_id.unique())
        unique_mppt_id = list(df_train.mppt_id.unique())
        get_training_inference = TrainingInference(df=df_mppt, df_train=df_train, df_test=df_test)
        for inv_id in unique_inv_id:
            for mppt_id in unique_mppt_id:
                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 = mppt_data.get_final_data(x_test=x_test, y_test=y_test, predictions=predictions)
                    logger.info(f'{df_result.shape}')
                except Exception as e:
                    logger.exception(f'Exception - {e}')
    except Exception as e:
        logger.exception(f'Exception - {e}')


if __name__ == '__main__':
    get_tag_details()

