"""Диалоги и аватарки юзербота — как в catcher."""

from __future__ import annotations

import time
from pathlib import Path
from typing import Optional

AVATARS_DIR = Path(__file__).resolve().parent.parent / "database" / "userbots" / "avatars"


def message_preview(message) -> str:
    if message is None:
        return ""
    text = (getattr(message, "message", None) or "").strip()
    if text:
        return " ".join(text.split())[:90]
    if getattr(message, "sticker", None):
        return "Стикер"
    if getattr(message, "photo", None):
        return "Фото"
    if getattr(message, "video", None) or getattr(message, "video_note", None):
        return "Видео"
    if getattr(message, "voice", None) or getattr(message, "audio", None):
        return "Аудио"
    if getattr(message, "document", None):
        return "Файл"
    return ""


def dialog_payload(dialog) -> dict:
    if dialog.is_user:
        kind = "user"
    elif dialog.is_group:
        kind = "group"
    else:
        kind = "channel"
    entity = dialog.entity
    photo = getattr(entity, "photo", None)
    photo_id = ""
    has_photo = bool(photo) and "Empty" not in type(photo).__name__
    if has_photo:
        photo_id = str(getattr(photo, "photo_id", None) or getattr(photo, "id", None) or "")
    return {
        "id": dialog.id,
        "title": (dialog.name or "").strip() or str(dialog.id),
        "kind": kind,
        "username": (getattr(entity, "username", None) or "").strip(),
        "unread": int(getattr(dialog, "unread_count", 0) or 0),
        "preview": message_preview(getattr(dialog, "message", None)),
        "has_photo": has_photo,
        "photo_id": photo_id,
    }


async def collect_dialogs(client, limit: int = 200) -> list[dict]:
    items: list[dict] = []
    async for dialog in client.iter_dialogs(limit=limit):
        items.append(dialog_payload(dialog))
    return items


async def fetch_dialog_photo(client, cache_key: str, chat_id: int) -> Optional[bytes]:
    AVATARS_DIR.mkdir(parents=True, exist_ok=True)
    cache = AVATARS_DIR / f"{cache_key}_{int(chat_id)}.jpg"
    if cache.is_file() and cache.stat().st_size > 0:
        age = time.time() - cache.stat().st_mtime
        if age < 15 * 60:
            return cache.read_bytes()
    try:
        data = await client.download_profile_photo(int(chat_id), file=bytes)
    except Exception:
        data = None
    if not data:
        if cache.is_file() and cache.stat().st_size > 0:
            return cache.read_bytes()
        return None
    try:
        cache.write_bytes(data)
    except Exception:
        pass
    return data
