import base64
from pathlib import Path
import filetype


class PromptedImage:
    """Read image and format it for LangChain model invocation."""
    def __init__(self, path: str):
        self.path = Path(path)
    
    def read(self) -> dict:
        """Read image file and return content formatted for LangChain model invocation.
        
        Returns:
            dict: Content dictionary with 'type' and 'image_url' keys for LangChain models
        """
        base64_image = self.get_data_base64()
        media_type = self.guess_media_type()
        return {
            "type": "image_url",
            "image_url": {
                "url": f"data:{media_type};base64,{base64_image}"
            }
        }
    
    def get_data_base64(self) -> str:
        with open(self.path, "rb") as f:
            image_data = f.read()
        base64_image = base64.b64encode(image_data).decode("utf-8")
        return base64_image

    def guess_media_type(self) -> str:
        ext = self.guess_extension()
        if ext == 'jpeg' or ext == 'jpg':
            return 'image/jpeg'
        elif ext == 'png':
            return 'image/png'
        elif ext == 'gif':
            return 'image/gif'
        elif ext == 'webp':
            return 'image/webp'
        else:
            raise ValueError(f"Unsupported image extension: {ext}")
        
    def guess_extension(self) -> str:
        return filetype.guess(self.path).EXTENSION

