from __future__ import annotations

import base64
import json

from mcp.server.fastmcp import FastMCP

from . import tools as _tools

mcp = FastMCP("memes")


@mcp.tool()
def list_memes(query: str | None = None) -> str:
    """Search meme templates by name or keyword. Returns a list of available memes with their IDs and metadata."""
    results = _tools.list_memes(query=query)
    return json.dumps(results, indent=2)


@mcp.tool()
def get_meme(template_id: str) -> str:
    """Get detailed info about a meme — description, humor, when to use, what each text line means."""
    return json.dumps(_tools.get_meme(template_id), indent=2)


@mcp.tool()
def gen_meme(template_id: str, text: dict[str, str]) -> list:
    """Generate a meme image. text is a dict like {"1": "top text", "2": "bottom text"}. Returns the image."""
    img_bytes = _tools.gen_meme(template_id, text=text)
    return [
        {
            "type": "image",
            "data": base64.b64encode(img_bytes).decode(),
            "mimeType": "image/png",
        }
    ]


def main():
    mcp.run()
