from importlib import import_module
from typing import Any, Optional

from mem0x.bootstrap.chunkers.base_chunker import BaseChunker
from mem0x.bootstrap.config import AddConfig
from mem0x.bootstrap.config.add_config import ChunkerConfig, LoaderConfig
from mem0x.bootstrap.helpers.json_serializable import JSONSerializable
from mem0x.bootstrap.loaders.base_loader import BaseLoader
from mem0x.bootstrap.models.data_type import DataType


class DataFormatter(JSONSerializable):
    """
    DataFormatter is an internal utility class which abstracts the mapping for
    loaders and chunkers to the data_type entered by the user in their
    .add or .add_local method call
    """

    def __init__(
        self,
        data_type: DataType,
        config: AddConfig,
        loader: Optional[BaseLoader] = None,
        chunker: Optional[BaseChunker] = None,
    ):
        """
        Initialize a dataformatter, set data type and chunker based on datatype.

        :param data_type: The type of the data to load and chunk.
        :type data_type: DataType
        :param config: AddConfig instance with nested loader and chunker config attributes.
        :type config: AddConfig
        """
        self.loader = self._get_loader(data_type=data_type, config=config.loader, loader=loader)
        self.chunker = self._get_chunker(data_type=data_type, config=config.chunker, chunker=chunker)

    @staticmethod
    def _lazy_load(module_path: str):
        module_path, class_name = module_path.rsplit(".", 1)
        module = import_module(module_path)
        return getattr(module, class_name)

    def _get_loader(
        self,
        data_type: DataType,
        config: LoaderConfig,
        loader: Optional[BaseLoader],
        **kwargs: Optional[dict[str, Any]],
    ) -> BaseLoader:
        """
        Returns the appropriate data loader for the given data type.

        :param data_type: The type of the data to load.
        :type data_type: DataType
        :param config: Config to initialize the loader with.
        :type config: LoaderConfig
        :raises ValueError: If an unsupported data type is provided.
        :return: The loader for the given data type.
        :rtype: BaseLoader
        """
        loaders = {
            DataType.YOUTUBE_VIDEO: "mem0x.bootstrap.loaders.youtube_video.YoutubeVideoLoader",
            DataType.PDF_FILE: "mem0x.bootstrap.loaders.pdf_file.PdfFileLoader",
            DataType.WEB_PAGE: "mem0x.bootstrap.loaders.web_page.WebPageLoader",
            DataType.QNA_PAIR: "mem0x.bootstrap.loaders.local_qna_pair.LocalQnaPairLoader",
            DataType.TEXT: "mem0x.bootstrap.loaders.local_text.LocalTextLoader",
            DataType.DOCX: "mem0x.bootstrap.loaders.docx_file.DocxFileLoader",
            DataType.SITEMAP: "mem0x.bootstrap.loaders.sitemap.SitemapLoader",
            DataType.XML: "mem0x.bootstrap.loaders.xml.XmlLoader",
            DataType.DOCS_SITE: "mem0x.bootstrap.loaders.docs_site_loader.DocsSiteLoader",
            DataType.CSV: "mem0x.bootstrap.loaders.csv.CsvLoader",
            DataType.MDX: "mem0x.bootstrap.loaders.mdx.MdxLoader",
            DataType.IMAGE: "mem0x.bootstrap.loaders.image.ImageLoader",
            DataType.UNSTRUCTURED: "mem0x.bootstrap.loaders.unstructured_file.UnstructuredLoader",
            DataType.JSON: "mem0x.bootstrap.loaders.json.JSONLoader",
            DataType.OPENAPI: "mem0x.bootstrap.loaders.openapi.OpenAPILoader",
            DataType.GMAIL: "mem0x.bootstrap.loaders.gmail.GmailLoader",
            DataType.NOTION: "mem0x.bootstrap.loaders.notion.NotionLoader",
            DataType.SUBSTACK: "mem0x.bootstrap.loaders.substack.SubstackLoader",
            DataType.YOUTUBE_CHANNEL: "mem0x.bootstrap.loaders.youtube_channel.YoutubeChannelLoader",
            DataType.DISCORD: "mem0x.bootstrap.loaders.discord.DiscordLoader",
            DataType.RSSFEED: "mem0x.bootstrap.loaders.rss_feed.RSSFeedLoader",
            DataType.BEEHIIV: "mem0x.bootstrap.loaders.beehiiv.BeehiivLoader",
            DataType.GOOGLE_DRIVE: "mem0x.bootstrap.loaders.google_drive.GoogleDriveLoader",
            DataType.DIRECTORY: "mem0x.bootstrap.loaders.directory_loader.DirectoryLoader",
            DataType.SLACK: "mem0x.bootstrap.loaders.slack.SlackLoader",
            DataType.DROPBOX: "mem0x.bootstrap.loaders.dropbox.DropboxLoader",
            DataType.TEXT_FILE: "mem0x.bootstrap.loaders.text_file.TextFileLoader",
            DataType.EXCEL_FILE: "mem0x.bootstrap.loaders.excel_file.ExcelFileLoader",
            DataType.AUDIO: "mem0x.bootstrap.loaders.audio.AudioLoader",
        }

        if data_type == DataType.CUSTOM or loader is not None:
            loader_class: type = loader
            if loader_class:
                return loader_class
        elif data_type in loaders:
            loader_class: type = self._lazy_load(loaders[data_type])
            return loader_class()

        raise ValueError(
            f"Cant find the loader for {data_type}.\
                    We recommend to pass the loader to use data_type: {data_type}"
        )

    def _get_chunker(self, data_type: DataType, config: ChunkerConfig, chunker: Optional[BaseChunker]) -> BaseChunker:
        """Returns the appropriate chunker for the given data type (updated for lazy loading)."""
        chunker_classes = {
            DataType.YOUTUBE_VIDEO: "mem0x.bootstrap.chunkers.youtube_video.YoutubeVideoChunker",
            DataType.PDF_FILE: "mem0x.bootstrap.chunkers.pdf_file.PdfFileChunker",
            DataType.WEB_PAGE: "mem0x.bootstrap.chunkers.web_page.WebPageChunker",
            DataType.QNA_PAIR: "mem0x.bootstrap.chunkers.qna_pair.QnaPairChunker",
            DataType.TEXT: "mem0x.bootstrap.chunkers.text.TextChunker",
            DataType.DOCX: "mem0x.bootstrap.chunkers.docx_file.DocxFileChunker",
            DataType.SITEMAP: "mem0x.bootstrap.chunkers.sitemap.SitemapChunker",
            DataType.XML: "mem0x.bootstrap.chunkers.xml.XmlChunker",
            DataType.DOCS_SITE: "mem0x.bootstrap.chunkers.docs_site.DocsSiteChunker",
            DataType.CSV: "mem0x.bootstrap.chunkers.table.TableChunker",
            DataType.MDX: "mem0x.bootstrap.chunkers.mdx.MdxChunker",
            DataType.IMAGE: "mem0x.bootstrap.chunkers.image.ImageChunker",
            DataType.UNSTRUCTURED: "mem0x.bootstrap.chunkers.unstructured_file.UnstructuredFileChunker",
            DataType.JSON: "mem0x.bootstrap.chunkers.json.JSONChunker",
            DataType.OPENAPI: "mem0x.bootstrap.chunkers.openapi.OpenAPIChunker",
            DataType.GMAIL: "mem0x.bootstrap.chunkers.gmail.GmailChunker",
            DataType.NOTION: "mem0x.bootstrap.chunkers.notion.NotionChunker",
            DataType.SUBSTACK: "mem0x.bootstrap.chunkers.substack.SubstackChunker",
            DataType.YOUTUBE_CHANNEL: "mem0x.bootstrap.chunkers.common_chunker.CommonChunker",
            DataType.DISCORD: "mem0x.bootstrap.chunkers.common_chunker.CommonChunker",
            DataType.CUSTOM: "mem0x.bootstrap.chunkers.common_chunker.CommonChunker",
            DataType.RSSFEED: "mem0x.bootstrap.chunkers.rss_feed.RSSFeedChunker",
            DataType.BEEHIIV: "mem0x.bootstrap.chunkers.beehiiv.BeehiivChunker",
            DataType.GOOGLE_DRIVE: "mem0x.bootstrap.chunkers.google_drive.GoogleDriveChunker",
            DataType.DIRECTORY: "mem0x.bootstrap.chunkers.common_chunker.CommonChunker",
            DataType.SLACK: "mem0x.bootstrap.chunkers.common_chunker.CommonChunker",
            DataType.DROPBOX: "mem0x.bootstrap.chunkers.common_chunker.CommonChunker",
            DataType.TEXT_FILE: "mem0x.bootstrap.chunkers.common_chunker.CommonChunker",
            DataType.EXCEL_FILE: "mem0x.bootstrap.chunkers.excel_file.ExcelFileChunker",
            DataType.AUDIO: "mem0x.bootstrap.chunkers.audio.AudioChunker",
        }

        if chunker is not None:
            return chunker
        elif data_type in chunker_classes:
            chunker_class = self._lazy_load(chunker_classes[data_type])
            chunker = chunker_class(config)
            chunker.set_data_type(data_type)
            return chunker

        raise ValueError(
            f"Cant find the chunker for {data_type}.\
                We recommend to pass the chunker to use data_type: {data_type}"
        )
