# retoor <retoor@molodetz.nl>

import hashlib
import logging
from fastapi import APIRouter, Request
from fastapi.responses import Response
from devplacepy.avatar import generate_avatar_svg
from devplacepy.cache import TTLCache
from devplacepy.config import SECONDS_PER_DAY

logger = logging.getLogger(__name__)
router = APIRouter()

_cache = TTLCache(ttl=SECONDS_PER_DAY, max_size=4096)
_CACHE_CONTROL = f"public, max-age={SECONDS_PER_DAY}, immutable"


@router.get("/{style}/{seed}")
async def avatar_proxy(request: Request, style: str, seed: str, size: int = 128):
    etag = '"' + hashlib.md5(f"{seed}:{size}".encode("utf-8")).hexdigest() + '"'
    headers = {"ETag": etag, "Cache-Control": _CACHE_CONTROL}

    if request.headers.get("if-none-match") == etag:
        return Response(status_code=304, headers=headers)

    svg = _cache.get(seed)
    if svg is None:
        svg = generate_avatar_svg(seed)
        _cache.set(seed, svg)
    return Response(content=svg, media_type="image/svg+xml", headers=headers)
