import pandas as pd
import json
import os
from pathlib import Path

from utils.documents_to_database import documents_to_database
from utils.convert_encoding_meta import convert_encoding_meta

#%% In[ ]:

# Get the current file's directory
try:
    # This will work when running as a script
    script_dir = Path(__file__).parent.parent
except NameError:
    # This will work in interactive environments
    script_dir = Path().absolute()

project_root = script_dir
fb_data_path = [os.path.join(project_root, 'import_data', 'data', 'Facebook', 'comments_and_reactions', 'comments.json')]

with open(fb_data_path[0], "r", encoding="raw-unicode-escape") as posts:
    comments_json = json.loads(convert_encoding_meta(posts.read()))

#%% In[ ]:
facebook_comments = []
for comment in comments_json['comments_v2']:
    if comment.get('data'):
        for data_item in comment['data']:
            if data_item.get('comment'):
                comment = data_item['comment']
                facebook_comments.append({"network": "Facebook",
                                          "type": "comments",
                                          "index": "rs_facebook_comments_and_reactions",
                                          "chemin": fb_data_path[0],
                                          "texte": comment["comment"],
                                          "creation_timestamp": comment["timestamp"]})

#%% In[ ]:
facebook_comments_df = pd.DataFrame(facebook_comments)

#%% In[ ]:
documents_to_database(facebook_comments_df)
