from typing import Union

from fastapi import HTTPException

from app.config import logger, minio_bucket_name, minio_client


def read_content_from_minio(filename: str) -> Union[str, bytes]:
    """
    Read content from MinIO storage based on the request filename.

    Args:
        request: The conversion request containing the filename

    Returns:
        The file content as string (for text files) or bytes (for binary files)

    Raises:
        HTTPException: If the file cannot be read or doesn't exist
        :param filename:
    """
    # Check if filename exists
    if not filename:
        logger.error("Filename is empty or invalid")
        raise HTTPException(
            status_code=400, detail="Filename is required"
        )

    # Read file from MinIO
    try:
        logger.info(
            f"Reading file '{filename}' from MinIO bucket '{minio_bucket_name}'")
        with minio_client.get_object(
                bucket_name=minio_bucket_name, object_name=filename
        ) as response:
            content_type = response.headers.get("content-type", "")
            logger.debug(f"File content type: {content_type}")

            if content_type.startswith("text/"):
                # Read as text (UTF-8)
                content = response.read().decode("utf-8")
                logger.debug(f"Read {len(content)} characters from text file")
            else:
                # Read as binary
                content = response.read()
                logger.debug(f"Read {len(content)} bytes from binary file")

            return content
    except Exception as e:
        error_msg = f"Error reading file '{filename}' from MinIO: {e!s}"
        logger.error(error_msg)
        raise HTTPException(
            status_code=500, detail=error_msg
        ) from e
