# app/src/notifications/channels/telegram.py

from __future__ import annotations

from aiogram.exceptions import TelegramRetryAfter

from src.notifications.models import NotificationMessage
from src.notifications.targets import NotificationTargetRegistry
from src.trading.journal.service import JournalService


class TelegramNotificationChannel:
    async def send(self, message: NotificationMessage) -> bool:
        bot = NotificationTargetRegistry.get_bot()
        chat_id = NotificationTargetRegistry.get_default_chat_id()

        if bot is None or chat_id is None:
            JournalService().log_warning(
                "notification_error",
                "Не удалось отправить Telegram-уведомление: получатель не настроен.",
                {
                    "title": message.title,
                    "priority": message.priority,
                    "dedupe_key": message.dedupe_key,
                },
            )
            return False

        try:
            await bot.send_message(
                chat_id=chat_id,
                text=message.text,
                parse_mode=message.parse_mode,
            )

            JournalService().log_info(
                "notification_sent",
                "Telegram-уведомление отправлено.",
                {
                    "title": message.title,
                    "priority": message.priority,
                    "dedupe_key": message.dedupe_key,
                },
            )

            return True

        except TelegramRetryAfter as exc:
            JournalService().log_warning(
                "notification_error",
                "Не удалось отправить Telegram-уведомление: Telegram ограничил частоту отправки.",
                {
                    "title": message.title,
                    "retry_after": exc.retry_after,
                    "priority": message.priority,
                    "dedupe_key": message.dedupe_key,
                },
            )
            return False

        except Exception as exc:
            JournalService().log_error(
                "notification_error",
                "Не удалось отправить Telegram-уведомление.",
                {
                    "title": message.title,
                    "error": str(exc),
                    "error_type": type(exc).__name__,
                    "priority": message.priority,
                    "dedupe_key": message.dedupe_key,
                },
            )
            return False