from io import StringIO, BytesIO
from typing import Union

from app.config import logger


def content_from_file(content: Union[str, bytes]) -> Union[StringIO, BytesIO]:
    """
    Prepare CSV content for reading, handling both string and bytes input.

    Args:
        content: CSV content as string or bytes

    Returns:
        StringIO or BytesIO object containing the CSV content

    Raises:
        TypeError: If content is neither string nor bytes
    """
    logger.info("Preparing to read CSV content")

    if isinstance(content, str):
        logger.debug("Using string content with StringIO")
        return StringIO(content)

    if isinstance(content, bytes):
        try:
            logger.debug("Attempting to convert bytes content to string")
            return StringIO(content.decode('utf-8'))
        except UnicodeDecodeError:
            logger.debug("Using binary content with BytesIO")
            return BytesIO(content)

    raise TypeError(f"Unsupported content type: {type(content)}")
