"""Уведомления пользователю и админу."""

from __future__ import annotations

import logging

from config import ADMIN_USER_IDS, ERROR_ALERTS_TO_ADMIN, bot

_log = logging.getLogger(__name__)


async def notify_chat(chat_id: int, text: str) -> bool:
    if not chat_id or not text:
        return False
    try:
        await bot.send_message(chat_id=chat_id, text=text)
        return True
    except Exception as e:
        _log.debug("notify_chat failed chat_id=%s: %s", chat_id, e)
        return False


async def notify_admin(text: str) -> bool:
    """Шлёт текст всем ADMIN_USER_IDS. True, если хотя бы один получил."""
    if not ADMIN_USER_IDS or not text:
        return False
    ok = False
    for admin_id in sorted(ADMIN_USER_IDS):
        if await notify_chat(admin_id, text):
            ok = True
    return ok


async def notify_user_and_maybe_admin(
    user_id: int | None,
    text: str,
    *,
    also_admin: bool = False,
) -> None:
    if user_id:
        await notify_chat(int(user_id), text)
    if also_admin and ERROR_ALERTS_TO_ADMIN and ADMIN_USER_IDS:
        # Не дублировать, если получатель уже один из админов
        skip_ids = {int(user_id)} if user_id else set()
        for admin_id in sorted(ADMIN_USER_IDS):
            if admin_id in skip_ids:
                continue
            await notify_chat(admin_id, text)
