import io

from PIL import Image

from memes_mcp.renderer import render_meme


def test_render_basic_meme():
    result = render_meme("drake", ["top text", "bottom text"])
    assert isinstance(result, bytes)
    assert len(result) > 1000

    img = Image.open(io.BytesIO(result))
    assert img.format == "PNG"
    assert img.width > 0
    assert img.height > 0


def test_render_with_size():
    result = render_meme(
        "fry", ["not sure if", "or just"], max_width=400, max_height=400
    )
    img = Image.open(io.BytesIO(result))
    assert img.width <= 400
    assert img.height <= 400


def test_render_single_line_template():
    result = render_meme("cmm", ["pineapple on pizza"])
    assert isinstance(result, bytes)
    img = Image.open(io.BytesIO(result))
    assert img.width > 0


def test_render_empty_lines():
    result = render_meme("drake", ["", ""])
    assert isinstance(result, bytes)
    img = Image.open(io.BytesIO(result))
    assert img.width > 0


def test_render_extra_lines_ignored():
    result = render_meme("drake", ["one", "two", "three", "four"])
    assert isinstance(result, bytes)


def test_render_jpg_extension():
    result = render_meme("drake", ["a", "b"], extension="jpg")
    assert isinstance(result, bytes)
    img = Image.open(io.BytesIO(result))
    assert img.format == "JPEG"


def test_render_unknown_template_raises():
    try:
        render_meme("nonexistent_xyz", ["a", "b"])
        assert False, "Should have raised ValueError"
    except ValueError as e:
        assert "Unknown template" in str(e)
