import logging
from asgiref.sync import sync_to_async
from bot.utils import send_event_message_async

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)


class NotificationService:
    def __init__(self, bot):
        self.bot = bot
        self.logger = logging.getLogger("NotificationService")
        self.logger.setLevel(logging.DEBUG)
        if not self.logger.handlers:
            handler = logging.StreamHandler()
            handler.setLevel(logging.DEBUG)
            handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
            self.logger.addHandler(handler)

    @sync_to_async
    def _get_all_clients(self):
        from webapp.models import Client
        clients = list(Client.objects.exclude(telegram_id__in=[None, "", "NULL"]))
        self.logger.info(f"Найдено клиентов для уведомления: {len(clients)}")
        return clients

    @sync_to_async
    def _prepare_results(self, results):
        return list(results.select_related('prize', 'participant__invoice'))

    async def notify_draw_start(self, lottery):
        clients = await self._get_all_clients()
        for client in clients:
            if not client.telegram_id:
                continue
            try:
                self.logger.debug(f"Отправка 'draw_started' клиенту {client.telegram_id}")
                await send_event_message_async(
                    event="draw_started",
                    bot=self.bot,
                    chat_id=int(client.telegram_id),
                    context_vars={"lottery": lottery, "client": client}
                )
            except Exception as e:
                self.logger.error(f"Ошибка отправки draw_started: {e}")

    # async def notify_draw_results(self, lottery, results):
    #     results_list = await self._prepare_results(results)
    #     clients = await self._get_all_clients()
    #     for client in clients:
    #         if not client.telegram_id:
    #             continue
    #         try:
    #             self.logger.debug(f"Отправка 'draw_finished' клиенту {client.telegram_id}")
    #             await send_event_message_async(
    #                 event="draw_finished",
    #                 bot=self.bot,
    #                 chat_id=int(client.telegram_id),
    #                 context_vars={"lottery": lottery, "client": client, "results": results_list}
    #             )
    #         except Exception as e:
    #             self.logger.error(f"Ошибка отправки draw_finished: {e}")

    async def notify_draw_results(self, lottery, results, context_vars=None):
        results_list = await self._prepare_results(results)
        clients = await self._get_all_clients()

        # 🔢 Подготовка суммы и списка победителей
        total_reward = sum(
            r.prize.reward for r in results_list if r.prize and r.prize.reward
        )

        winners_lines = []
        for r in results_list:
            try:
                account_id = r.participant.invoice.ext_id
                prize_amount = r.prize.reward
                winners_lines.append(f"• Счёт {account_id} — {prize_amount:,.2f}₩")
            except Exception:
                continue

        winners_list = "\n".join(winners_lines)

        for client in clients:
            if not client.telegram_id:
                continue
            try:
                self.logger.debug(f"Отправка 'draw_finished' клиенту {client.telegram_id}")
                await send_event_message_async(
                    event="draw_finished",
                    bot=self.bot,
                    chat_id=int(client.telegram_id),
                    context_vars={
                        **(context_vars or {}),
                        "lottery": lottery,
                        "client": client,
                        "results": results_list,
                        "total_reward": f"{total_reward:,.2f}",
                        "winners_list": winners_list
                    }
                )
            except Exception as e:
                self.logger.error(f"Ошибка отправки draw_finished: {e}")

                
                
    async def notify_prize_status_update(self, client, result):
        try:
            if client.telegram_id:
                self.logger.debug(f"Отправка 'winner_announced' клиенту {client.telegram_id}")
                await send_event_message_async(
                    event="winner_announced",
                    bot=self.bot,
                    chat_id=int(client.telegram_id),
                    context_vars={"client": client, "result": result, "prize": result.prize}
                )
        except Exception as e:
            self.logger.error(f"Ошибка отправки winner_announced: {e}")

    async def notify_binding_complete(self, client):
        try:
            if client.telegram_id:
                self.logger.debug(f"Отправка 'binding_complete' клиенту {client.telegram_id}")
                await send_event_message_async(
                    event="binding_complete",
                    bot=self.bot,
                    chat_id=int(client.telegram_id),
                    context_vars={"client": client}
                )
        except Exception as e:
            self.logger.error(f"Ошибка отправки binding_complete: {e}")
