from typing import Dict, Union, List

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


class MarkdownTxtConverter(BaseConverter):
    def __init__(self, content: Union[str, bytes]):
        super().__init__(content)
        self.metadata = None
        self.markdown_content = None

    def read_file(self) -> None:
        txt_file = content_from_file(self.content)
        # For markdown, we might want to read it as a single string
        # and then process it, rather than immediately converting to a DataFrame
        self.markdown_content = txt_file.read()

    def add_metadata(self) -> None:
        # Since we're not using a DataFrame for markdown,
        # we'll store metadata separately
        self.metadata = {
            "index": "markdown_txt",
            "type": "markdown",
            "network": "Generic"
        }

    def convert_columns(self) -> None:
        # For markdown, we might not have columns in the traditional sense
        # Instead, we could parse the markdown and extract structured data
        # This is a placeholder for that logic
        pass

    def rename_columns(self) -> None:
        # Again, for markdown, we might not have columns to rename
        # This method could be used to standardize any extracted data
        pass

    def clean_data(self) -> None:
        # Clean the markdown content
        # For example, remove any unwanted characters or formatting
        self.markdown_content = self.markdown_content.strip()

    def convert(self) -> List[Dict]:
        """Convert the markdown content to the standardized format."""
        try:
            self.read_file()
            self.add_metadata()
            self.convert_columns()
            self.rename_columns()
            self.clean_data()

            # Process the markdown content and convert it to the desired format
            # This is a placeholder for the actual conversion logic
            result = [{
                "content": self.markdown_content,
                **self.metadata
            }]

            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_markdown_txt(content: Union[str, bytes]) -> List[Dict]:
    """
    Convert markdown txt content to a standardized format.

    Args:
        content (Union[str, bytes]): The txt content of the markdown.

    Returns:
        ConversionResponse: An object containing the converted data, status, and metadata.
    """
    logger.info(f"Starting conversion of {len(content)} bytes")
    converter = MarkdownTxtConverter(content)

    return converter.convert()
