import datetime
from typing import Dict, Union, List

import pandas as pd

from app.convert.base_converter import BaseConverter
from app.convert.utils.content_from_file import content_from_file


class LinkedInSharesConverter(BaseConverter):
    def read_file(self) -> None:
        """Read the file content into a DataFrame."""
        csv_file = content_from_file(self.content)
        self.df = pd.read_csv(csv_file)

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

    def convert_columns(self) -> None:
        self.df["Date"] = self.df["Date"].apply(
            lambda x: int(datetime.datetime.fromisoformat(x).timestamp())
        )
        self.df["ShareCommentary"] = self.df["ShareCommentary"].astype(str)

    def rename_columns(self) -> None:
        self.df = self.df.rename(columns={
            "ShareLink": "uri",
            "ShareCommentary": "content",
            "Date": "creation_timestamp"
        })

    def clean_data(self) -> None:
        """Clean and preprocess the DataFrame."""
        self.df = self.df.fillna("")
        self.df = self.df.drop_duplicates(
            subset=["content", "creation_timestamp"])
        self.df = self.df[self.df["content"].str.strip() != ""]


def convert_linkedin_shares_csv(content: Union[str, bytes]) -> List[Dict]:
    """
    Convert LinkedIn shares CSV content to a standardized format.
    """
    converter = LinkedInSharesConverter(content)
    return converter.convert()
