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


def get_tags_data(tags, start_timestamp, end_timestamp):
    try:
        df_merged = pd.DataFrame()
        for inv_id in list(tags['inv_id'].unique()):

            df = tags[tags['inv_id'] == inv_id]
            df_tags_id = df[['tag_id', 'tag_name', 'inv_id', 'parameter_name', 'mppt_id',
                             'mppt_id_with_equipment']]
            df_tags_id.reset_index(drop=True, inplace=True)
            tags_dict = df_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}')

