import gc

import pandas as pd
from loguru import logger
import warnings
import tracemalloc
from scripts.utils.mongo_utils import MongoConnect
from scripts.constants.app_configuration import Mongo
from scripts.constants.app_constants import MongoConstants
warnings.filterwarnings('ignore')


def get_raw_predicted_tags():
    try:
        mongo_conn = MongoConnect(uri=Mongo.mongo_uri, database=MongoConstants.db,
                                  collection=MongoConstants.collection)
        if mongo_conn is None:
            logger.info(f'mongodb is not connected, please check')
        else:
            logger.info(f'mongodb is connected')
            logger.debug(f'mongo conn - {mongo_conn}')
            raw_tags_dict = mongo_conn.find_one({"$and": [{"id": "dalmia_string_level_tags"}, {"city": "ariyalur"},
                                                          {"tags_property": "raw"}]})
            req_tags = raw_tags_dict['input_data']
            logger.info(f'req raw tags length - {len(req_tags)}')
            df_raw_tags = pd.DataFrame.from_dict(req_tags, orient='index')

            predicted_tags_dict = mongo_conn.find_one({"$and": [{"id": "dalmia_string_level_tags"}, {"city": "ariyalur"},
                                                                {"tags_property": "predicted"}]})
            predicted_tags = predicted_tags_dict['input_data']
            logger.info(f'req predicted tags length - {len(predicted_tags)}')
            df_predicted_tags = pd.DataFrame.from_dict(predicted_tags, orient='index')

            df_raw_tags.reset_index(inplace=True)
            df_raw_tags.rename(columns={'index': 'tag_name'}, inplace=True)
            df_predicted_tags.reset_index(inplace=True)
            df_predicted_tags.rename(columns={'index': 'tag_name'}, inplace=True)

            mppt_coefficients = mongo_conn.find_one({"$and": [{"id": "dalmia_string_level_tags"}, {"city": "ariyalur"},
                                                              {"tags_property": "mppt_coefficients"}]})

            coefficients_dict = mppt_coefficients['input_data']
            logger.info(f'req coefficients dict length - {len(coefficients_dict)}')
            df_coefficients = pd.DataFrame.from_dict(coefficients_dict, orient='index')
            df_coefficients.reset_index(inplace=True)
            df_coefficients.rename(columns={'index': 'inv_id_mppt_id'}, inplace=True)

            print(tracemalloc.get_traced_memory())

            raw_tags_dict.clear()
            predicted_tags_dict.clear()
            coefficients_dict.clear()
            del req_tags
            del predicted_tags

            print(f'memory allocation - {tracemalloc.get_traced_memory()}')
            gc.collect()
            tracemalloc.reset_peak()
            print(f'memory allocation - {tracemalloc.get_traced_memory()}')
            tracemalloc.clear_traces()
            print(f'memory allocation - {tracemalloc.get_traced_memory()}')

            return df_raw_tags, df_predicted_tags, df_coefficients
    except Exception as e:
        logger.exception(f'Exception - {e}')
