import base64
from typing import Optional

import dataiku
from backend.utils.logging_utils import get_logger

logger = get_logger(__name__)


def get_empty_image_base64() -> str:
    # This is a 1x1 transparent PNG encoded in base64
    return "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/wcAAgAB/ivFZ8sAAAAASUVORK5CYII="


def b64encode_image_from_full_folder_id(file_path: Optional[str] = None, full_folder_id: Optional[str] = None) -> str:
    """
    Wrapper around b64_encode_image_from_path to handle the complete
    folder id coming from sources and format the img string
    If given params are not good return an empty image
    """

    if file_path and full_folder_id and "." in full_folder_id and "." in file_path:
        folder_id = full_folder_id.split(".")[-1]
        file_format = file_path.split(".")[-1]
        project_key = full_folder_id.split(".")[0] or dataiku.api_client().get_default_project().project_key
        b64_image = b64encode_image_from_path(file_path=file_path, project_key=project_key, folder_id=folder_id)
        return f"data:image/{file_format};base64,{b64_image}"

    return get_empty_image_base64()


def b64encode_image_from_path(file_path: str, project_key: str, folder_id: Optional[str] = None) -> str:
    """
    Encodes an image from a specified file path to a base64-encoded string.

    Parameters:
    - file_path (str): The path to the image file to be encoded. This path must point to a valid
    image file in the managed folder configured in the webapp.

    Returns:
    - str: A base64-encoded string representing the image. This string can be directly used in data URIs
        or for storage in text-based formats.
    """
    try:
        file_folder = dataiku.Folder(lookup=folder_id, project_key=project_key)

        with file_folder.get_download_stream(file_path) as stream:
            file_content = stream.read()
        base64_encoded = base64.b64encode(file_content)
        img_b64 = base64_encoded.decode("utf-8")
        return img_b64
    except Exception as err:
        logger.exception(f"Error getting file {file_path} from upload folder {folder_id}, error: {err}")
        return get_empty_image_base64()
