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):
    try:
        df_merged = pd.DataFrame()
        for inv_id in list(df_input_tags['inv_id'].unique()):
            df = df_input_tags[df_input_tags['inv_id'] == inv_id]
            df_tags_id = df[['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
            if df_merged.empty:
                df_merged = df_data
            else:
                df_merged = pd.concat([df_merged, df_data], axis=0)
            logger.info(f' for inv- {inv_id}, {df_data.shape}')
            logger.info(f'{df_merged.shape}')
        df_merged['date'] = df_merged['datetime'].dt.date
        df_merged['hour'] = df_merged['datetime'].dt.hour
        logger.info(f'Final shape of merged dataframe = {df_merged.shape}')
        df_merged.reset_index(drop=True, inplace=True)
        return df_merged
    except Exception as e:
        logger.exception(f'Exception - {e}')

