import base64
import mimetypes
import logging
from pathlib import Path
from typing import Any, Dict
from tools.utils import ToolError

logger = logging.getLogger("MooseCP")

async def handle(args: Dict[str, Any]):
    """
    Reads an image file from disk and returns it as a base64 encoded string 
    within an MCP ImageContent object.
    """
    path_str = args.get("path")
    if not path_str:
        raise ToolError("Missing path argument")
    
    path = Path(path_str)
    
    # Validate that the file has an image-like MIME type
    mime_type, _ = mimetypes.guess_type(path_str)
    if not mime_type or not mime_type.startswith("image/"):
        raise ToolError(f"File {path_str} is not a supported image format.")
    
    try:
        data = base64.b64encode(path.read_bytes()).decode("utf-8")
        return [{"type": "image", "data": data, "mimeType": mime_type}]
    except Exception as e:
        raise ToolError(f"Error reading image: {str(e)}")
