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

base_path = 'data_folder'


def get_tags_data(mppt_tags, start_timestamp, end_timestamp):
    try:
        get_tags = GetTags(base_path=base_path)
        df_merged = pd.DataFrame()
        for inv_id in list(mppt_tags['inv_id'].unique()):
            df_tags_id = get_tags.get_tags_id(df=mppt_tags, inv_id=inv_id)
            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)
        # df_merged.to_csv(f'{base_path}/df_merged.csv', index=False)
        return df_merged
    except Exception as e:
        logger.exception(f'Exception - {e}')

