"""Notifier — sends alerts to chat IDs via MTProto or bot."""

from __future__ import annotations

import logging
from typing import Any, Awaitable, Callable

from ._formatter import format_alert_html
from ._types import MonitorAlert

logger = logging.getLogger(__name__)

SendFn = Callable[..., Awaitable[Any]]


class Notifier:
    """Sends MonitorAlert to target chats.

    Supports two modes:
    - MTProto: sends as user account (account_send_message)
    - Bot: sends via registered bot (send_message)
    """

    def __init__(
        self,
        send_fn: SendFn,
        chat_ids: list[int | str],
        *,
        mode: str = "mtproto",  # "mtproto" or "bot"
        account: str = "main",
        bot: str = "",
    ):
        self._send_fn = send_fn
        self._chat_ids = chat_ids
        self._mode = mode
        self._account = account
        self._bot = bot

    async def notify(self, alert: MonitorAlert) -> None:
        """Send alert to all target chats. Errors are logged, not raised."""
        html = format_alert_html(alert)
        for chat_id in self._chat_ids:
            try:
                if self._mode == "bot":
                    await self._send_fn(self._bot, chat_id, html, parse_mode="HTML")
                else:
                    await self._send_fn(
                        self._account, str(chat_id), html, parse_mode="html",
                    )
            except Exception as e:
                logger.error("Failed to send alert to %s: %s", chat_id, e)
