"""Per-user avatar storage — users/{user_id}/avatar.png (128×128 PNG)."""

from __future__ import annotations

import io
from pathlib import Path

from niannian.users.paths import user_root

MAX_SIZE = 512 * 1024
AVATAR_SIZE = 128


def avatar_path(home: Path, user_id: str) -> Path:
    return user_root(home, user_id) / "avatar.png"


def has_avatar(home: Path, user_id: str) -> bool:
    return avatar_path(home, user_id).is_file()


def delete_avatar(home: Path, user_id: str) -> None:
    path = avatar_path(home, user_id)
    if path.is_file():
        path.unlink()


def save_avatar(home: Path, user_id: str, data: bytes) -> Path:
    if not data:
        raise ValueError("avatar empty")
    if len(data) > MAX_SIZE:
        raise ValueError(f"avatar exceeds {MAX_SIZE} bytes")

    try:
        from PIL import Image
    except ImportError as exc:
        raise RuntimeError("Pillow required for avatar resize") from exc

    try:
        image = Image.open(io.BytesIO(data))
        image.load()
    except OSError as exc:
        raise ValueError("invalid image format") from exc

    image = image.convert("RGBA")
    image = image.resize((AVATAR_SIZE, AVATAR_SIZE), Image.Resampling.LANCZOS)

    path = avatar_path(home, user_id)
    path.parent.mkdir(parents=True, exist_ok=True)

    buf = io.BytesIO()
    image.save(buf, format="PNG", optimize=True)
    path.write_bytes(buf.getvalue())
    return path
