"""MCP server for reading clipboard images."""

import base64
import io
from mcp.server.fastmcp import FastMCP

mcp = FastMCP("clipboard-image")


@mcp.tool()
def get_clipboard_image() -> dict:
    """
    Get the current image from the clipboard.
    Returns the image as base64 encoded data that can be displayed by Claude.
    """
    try:
        from PIL import ImageGrab

        # Grab image from clipboard
        image = ImageGrab.grabclipboard()

        if image is None:
            return {"error": "No image found in clipboard. Please copy an image first."}

        # Check if it's a list of file paths (when files are copied)
        if isinstance(image, list):
            return {"error": f"Clipboard contains file paths, not an image: {image}"}

        # Convert image to PNG bytes
        buffer = io.BytesIO()
        image.save(buffer, format="PNG")
        image_bytes = buffer.getvalue()

        # Encode to base64
        base64_image = base64.standard_b64encode(image_bytes).decode("utf-8")

        return {
            "type": "image",
            "media_type": "image/png",
            "data": base64_image,
            "width": image.width,
            "height": image.height,
        }

    except ImportError:
        return {"error": "Pillow library not installed. Run: pip install Pillow"}
    except Exception as e:
        return {"error": f"Failed to read clipboard image: {str(e)}"}


def main():
    """Run the MCP server."""
    mcp.run()


if __name__ == "__main__":
    main()
