# retoor <retoor@molodetz.nl>

import hashlib
import logging
from typing import Optional

from devplacepy.avatar import generate_avatar_svg

logger = logging.getLogger(__name__)


def background_color(username: Optional[str]) -> str:
    seed = username or "?"
    return hashlib.md5(seed.encode("utf-8")).hexdigest()[:6]


def avatar_payload(username: Optional[str]) -> dict:
    seed = username or "anonymous"
    return {"b": background_color(seed), "i": f"u/{seed}.png"}


def render_png(username: str, size: int = 128) -> bytes:
    import cairosvg

    svg = generate_avatar_svg(username)
    return cairosvg.svg2png(
        bytestring=svg.encode("utf-8"), output_width=size, output_height=size
    )
