import json
from typing import Dict, Union, List

import pandas as pd

from app.config import logger
from app.convert.base_converter import BaseConverter
from app.convert.utils.encode_utf8 import encode_utf8


class FacebookBusinessPostsConverter(BaseConverter):
    def read_file(self) -> None:
        content = encode_utf8(self.content)
        self.datadict = json.loads(content)

        posts_medias = []
        for post in self.datadict:
            data_post_items = post['data']
            texte_post_list = [item['post'] for item in data_post_items if
                               item.get('post')]
            texte = "\n".join(texte_post_list)

            for attachment in post['attachments']:
                if attachment.get('data'):
                    for data_item in attachment['data']:
                        if data_item.get('media'):
                            media = data_item['media']
                            posts_medias.append({
                                "chemin": [media["uri"]],
                                "texte": texte,
                                "creation_timestamp": media[
                                    "creation_timestamp"]
                            })

        self.df = pd.DataFrame(posts_medias).explode(['chemin'])

    def add_metadata(self) -> None:
        self.df = self.df.assign(
            index="facebook_business_posts",
            type="posts",
            network="FacebookBusiness"
        )

    def convert_columns(self) -> None:
        self.df['creation_timestamp'] = self.df['creation_timestamp'].astype(
            int)

    def rename_columns(self) -> None:
        # No column renaming needed for this converter
        pass

    def clean_data(self) -> None:
        self.df['url'] = ""
        self.df.fillna(value="", inplace=True)


def convert_facebook_business_posts_json(content: Union[str, bytes]) -> List[
    Dict]:
    logger.info(f"Starting conversion of {len(content)} bytes")
    converter = FacebookBusinessPostsConverter(content)

    return converter.convert()
