# retoor <retoor@molodetz.nl>

import logging

logger = logging.getLogger(__name__)


def avatar_url(style: str, seed: str, size: int = 128) -> str:
    return f"/avatar/{style}/{seed}?size={size}"


def avatar_seed(user) -> str:
    if not user:
        return ""
    return user.get("avatar_seed") or user.get("username") or ""


def generate_avatar_svg(seed: str) -> str:
    try:
        from multiavatar.multiavatar import multiavatar

        svg = multiavatar(seed, None, None)
        if svg and svg.strip().startswith("<svg"):
            return svg
    except Exception as e:
        logger.exception(e)
        logger.warning(f"Avatar generation failed for {seed}: {e}")
    initial = seed[:1].upper() if seed else "?"
    return (
        '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">'
        f'<rect width="100" height="100" rx="50" fill="#b73f1e"/>'
        f'<text x="50" y="65" text-anchor="middle" fill="white" font-size="40" font-weight="700" font-family="sans-serif">{initial}</text></svg>'
    )
