import json
import datetime
from typing import Dict, Union, List

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 InstagramStoriesConverter(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_stories",
            type="stories",
            network="Instagram"
        )

    def convert_columns(self) -> None:
        stories = self.datadict.get('ig_stories', [])
        self.df = pd.DataFrame(stories)
        self.df['creation_timestamp'] = self.df['creation_timestamp'].apply(
            lambda x: datetime.datetime.fromtimestamp(x).isoformat()
        )

    def rename_columns(self) -> None:
        self.df.rename(columns={
            "title": "texte",
            "uri": "chemin"
        }, inplace=True)

    def clean_data(self) -> None:

        self.df['url'] = ""
        self.df.drop(columns=['creation_timestamp', 'media_metadata',
                              'cross_post_source'], inplace=True)
        self.df.fillna(value="", inplace=True)

    def convert(self) -> List[Dict]:
        try:
            self.read_file()
            self.convert_columns()
            self.add_metadata()
            self.rename_columns()
            self.clean_data()
            result = self.df.to_dict('records')

            logger.info(f"Conversion completed successfully")
            return result

        except Exception as e:
            logger.exception(f"Unexpected error during conversion: {str(e)}")
            raise ValueError(f"Unexpected error during conversion: {str(e)}")


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

    return converter.convert()
