import pandas as pd
from loguru import logger
from scripts.core.data_puller_push.data_puller import KairosQuery


def get_tags_data(df_input_tags, start_timestamp, end_timestamp, inv_id, mppt_id):
    try:
        df_tags_id = df_input_tags[['tag_id', 'tag_name', 'inv_id', 'parameter_name', 'mppt_id']]

        df_tags_id.reset_index(drop=True, inplace=True)

        current_voltage_tags_only = [data for data in df_tags_id['parameter_name']
                                     if any([x in data for x in ['current', 'voltage']])]
        req_data_list = [data for data in current_voltage_tags_only if 'Potential' not in data]
        req_data_list = [data for data in req_data_list if 'Degradation' not in data]
        df_req_tags_id = df_tags_id.loc[df_tags_id['parameter_name'].isin(req_data_list)]
        df_req_tags_id.reset_index(drop=True, inplace=True)

        tags_dict = df_req_tags_id[['tag_id', 'parameter_name']].set_index('tag_id').T.to_dict(orient="records")[0]
        tags_dict['site_107$dept_140$line_371$equipment_4115$tag_15828'] = 'tilt_irradiance'
        df_data = KairosQuery(start_timestamp=start_timestamp,
                              end_timestamp=end_timestamp,
                              tag_dict=tags_dict).kairos_data_import()
        df_data['inv_id'] = inv_id
        df_data['mppt_id'] = mppt_id
        logger.info(f' for inv- {inv_id}, {df_data.shape}')
        df_data['date'] = df_data['datetime'].dt.date
        df_data['hour'] = df_data['datetime'].dt.hour
        df_data.drop(['date'], axis=1, inplace=True)
        df_data.drop(df_data[df_data['hour'].between(left=19, right=23, inclusive='both')].index, inplace=True, axis=0)
        df_data.drop(df_data[df_data['hour'].between(left=0, right=5, inclusive='both')].index, inplace=True, axis=0)
        logger.info(f'Final shape of merged dataframe = {df_data.shape}')
        df_data.reset_index(drop=True, inplace=True)
        return df_data
    except Exception as e:
        logger.exception(f'Exception - {e}')

