import json
from typing import Union, List, Dict

import pandas as pd

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


class FacebookCommentsConverter(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="facebook_comments",
            type="comments",
            network="Facebook"
        )

    def convert_columns(self) -> None:
        facebook_comments = []
        for comment in self.datadict['comments_v2']:
            if comment.get('data'):
                for data_item in comment['data']:
                    if data_item.get('comment'):
                        comment_data = data_item['comment']
                        facebook_comments.append({
                            "texte": comment_data["comment"],
                            "creation_timestamp": comment_data["timestamp"]
                        })

        self.df = pd.DataFrame(facebook_comments)
        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['chemin'] = ""
        self.df.fillna(value="", inplace=True)


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

    return converter.convert()
