import uuid
from io import BytesIO
from pathlib import Path

from PIL import Image

from app.core.config import settings


def avatar_rel_path(user_id: str, student_id: str) -> str:
    return f"{user_id}/avatars/{student_id}.jpg"


def save_avatar(user_id: str, student_id: str, content: bytes) -> str:
    rel = avatar_rel_path(user_id, student_id)
    full = Path(settings.UPLOAD_DIR) / rel
    full.parent.mkdir(parents=True, exist_ok=True)

    image = Image.open(BytesIO(content))
    if image.mode not in ("RGB", "L"):
        image = image.convert("RGB")
    image.thumbnail((256, 256), Image.Resampling.LANCZOS)
    image.save(full, format="JPEG", quality=85, optimize=True)
    return rel


def delete_avatar_file(avatar_path: str | None) -> None:
    if not avatar_path:
        return
    full = Path(settings.UPLOAD_DIR) / avatar_path
    if full.is_file():
        full.unlink()
