import contextlib
import io

from PIL import Image


def generate_thumbnail(data: bytes, mime_type: str) -> bytes:
    img = Image.open(io.BytesIO(data))
    with contextlib.suppress(EOFError):
        img.seek(0)
    if img.mode not in ("RGB", "RGBA"):
        img = img.convert("RGBA" if img.mode == "P" and "transparency" in img.info else "RGB")
    img.thumbnail((400, 400), Image.LANCZOS)
    buf = io.BytesIO()
    img.save(buf, format="WEBP", quality=80)
    return buf.getvalue()
