import json
from typing import Union, List, Dict

import pandas as pd

from app.config import logger
from app.convert.base_converter import BaseConverter
from app.convert.utils.content_from_file import content_from_file
from app.convert.utils.convert_encoding_meta import convert_encoding_meta


class InstagramCommentsConverter(BaseConverter):
    def read_file(self) -> None:
        json_file = content_from_file(self.content)
        content = convert_encoding_meta(json_file.read())
        self.datadict = json.loads(content)

    def add_metadata(self) -> None:
        self.df = self.df.assign(
            index="instagram_comments",
            type="comments",
            network="Instagram",
        )

    def convert_columns(self) -> None:
        ig_comments = []
        for comment in self.datadict.get('comments_reels_comments',
                                         []) + self.datadict.get(
                'post_comments_1', []):
            ig_comments.append({
                "content": comment['string_map_data']['Comment']['value'],
                'creation_timestamp': int(
                    comment['string_map_data']['Time']['timestamp']),
                'index': self.df.index,
                'type': self.df.type,
                'network': self.df.network,
                'url': "",
                'chemin': ""
            })
        self.df = pd.DataFrame(ig_comments)

    def rename_columns(self) -> None:
        # No need to rename columns as they are already in the desired format
        pass

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


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

    return converter.convert()
