import datetime

import pandas as pd
import json

from utils.get_ids import get_idtypedocument, get_idreseausocial
from utils.documents_to_database import documents_to_database
from utils.convert_encoding_meta import convert_encoding_meta

# In[ ]:
instagram_data_path = 'data/Instagram/content/stories.json'
with open(instagram_data_path, "r", encoding="raw-unicode-escape") as posts:
    stories_json = json.loads(convert_encoding_meta(posts.read()))

# In[ ]:
ig_stories_df = pd.DataFrame(stories_json['ig_stories'])

# In[ ]:
ig_stories_df['datepublication'] = ig_stories_df['creation_timestamp'].apply(
    lambda x: datetime.datetime.fromtimestamp(x).isoformat())

# In[ ]:
ig_stories_df['index'] = "rs_instagram_content"
ig_stories_df['type'] = "stories"
ig_stories_df['network'] = "Instagram"
ig_stories_df['chemin'] = instagram_data_path

# In[ ]:
ig_stories_df.rename(columns={"title": "texte"}, inplace=True)

# In[ ]:
del ig_stories_df['creation_timestamp']
del ig_stories_df['media_metadata']
del ig_stories_df['cross_post_source']
del ig_stories_df['ai_stickers']
del ig_stories_df['dubbing_info']

# In[ ]:
ig_stories_df.fillna(value="", inplace=True)

# In[ ]:
ig_stories_df.drop_duplicates(subset=['texte', 'datepublication'], inplace=True)

# In[ ]:
# Filter empty texte
ig_stories_df = ig_stories_df[~ig_stories_df['texte'].str.strip('\n').str.strip().eq('')]

# In[ ]:
documents_to_database(ig_stories_df)
