import datetime
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.content_from_file import content_from_file


class LinkedInCommentsConverter(BaseConverter):
    def read_file(self) -> None:
        csv_file = content_from_file(self.content)
        self.df = pd.read_csv(csv_file,
                              escapechar='\\',
                              skipinitialspace=True)
        # Output first 5 rows to logger
        print(self.df.head(5))

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

    def convert_columns(self) -> None:
        self.df['Message'] = (
            self.df['Message'].str.replace(r'[\r\n\t]+', ' ', regex=True))
        self.df = self.df[self.df['Message'] != ""]
        self.df = self.df.drop_duplicates().reset_index(drop=True)
        self.df["creation_timestamp"] = self.df["Date"].apply(
            lambda x: int(datetime.datetime.fromisoformat(x).timestamp())
        )
        del self.df["Date"]

    def rename_columns(self) -> None:
        self.df.rename(columns={
            "Link": "url",
            "Message": "content"
        }, inplace=True)

    def clean_data(self) -> None:
        self.df["content"] = self.df["content"].apply(lambda x: str(x))
        self.df["chemin"] = ""
        self.df.fillna(value="", inplace=True)

    def convert(self) -> List[Dict]:
        try:
            self.read_file()
            self.add_metadata()
            self.convert_columns()
            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_linkedin_comments_csv(content: Union[str, bytes]) -> List[Dict]:
    logger.info(f"Starting conversion of {len(content)} bytes")

    converter = LinkedInCommentsConverter(content)
    return converter.convert()
