from __future__ import annotations

import json
import logging
from urllib import parse, request


logger = logging.getLogger(__name__)


class WorkerNotifier:
    def notify(self, text: str) -> None:
        raise NotImplementedError


class NullNotifier(WorkerNotifier):
    def notify(self, text: str) -> None:
        return


class TelegramNotifier(WorkerNotifier):
    def __init__(self, bot_token: str, user_ids: set[int]) -> None:
        self.bot_token = bot_token
        self.user_ids = user_ids

    def notify(self, text: str) -> None:
        for user_id in self.user_ids:
            try:
                payload = parse.urlencode(
                    {
                        "chat_id": str(user_id),
                        "text": text[:3500],
                    }
                ).encode("utf-8")
                req = request.Request(
                    f"https://api.telegram.org/bot{self.bot_token}/sendMessage",
                    data=payload,
                    headers={"Content-Type": "application/x-www-form-urlencoded"},
                )
                with request.urlopen(req, timeout=10) as response:
                    json.load(response)
            except Exception:
                logger.exception("Failed to send Telegram notification")
