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 InstagramPostsConverter(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_posts",
            type="posts",
            network="Instagram"
        )

    def convert_columns(self) -> None:
        posts_medias = []
        for post in self.datadict:
            medias = post['media']
            if len(medias) == 1:
                media = medias[0]
                posts_medias.append({
                    "chemin": [media["uri"]],
                    "texte": media["title"],
                    "creation_timestamp": media["creation_timestamp"]
                })
            else:
                title = post['title']
                creation_timestamp = post['creation_timestamp']
                list_uris = [media['uri'] for media in medias]
                posts_medias.append({
                    "chemin": list_uris,
                    "texte": title,
                    "creation_timestamp": creation_timestamp
                })

        self.df = pd.DataFrame(posts_medias).explode(['chemin'])
        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:
        super().clean_data()
        self.df['url'] = ""
        self.df.fillna(value="", inplace=True)


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

    return converter.convert()
