# retoor <retoor@molodetz.nl>

from __future__ import annotations

from devplacepy.services.base import BaseService

from . import store

BATCH_LIMIT = 50


class TelegramOutboxService(BaseService):
    title = "Telegram notifications"
    description = (
        "Delivers notifications to users who paired Telegram and opted a "
        "notification type into the Telegram channel. Drains the telegram_outbox "
        "queue on the service lock owner, where the Telegram bot worker runs, and "
        "sends each message as markdown. Rows wait when the bot is not running, so "
        "nothing is lost. Off by default for every notification type."
    )
    default_enabled = True

    def __init__(self) -> None:
        super().__init__(name="telegram_outbox", interval_seconds=2)
        self._delivered = 0
        self._failed = 0

    async def run_once(self) -> None:
        from devplacepy.services.manager import service_manager

        telegram = service_manager.get_service("telegram")
        if (
            telegram is None
            or not telegram.is_enabled()
            or not telegram.worker_alive()
        ):
            return
        rows = store.pending_outbox(BATCH_LIMIT)
        for row in rows:
            delivered = await telegram.send_markdown(int(row["chat_id"]), row["text"])
            if delivered:
                store.mark_outbox_sent(row["id"])
                self._delivered += 1
            else:
                store.mark_outbox_failed(row["id"], int(row.get("attempts", 0)))
                self._failed += 1
        store.prune_outbox()
        if rows:
            self.log(f"drained {len(rows)} telegram notification(s)")

    def collect_metrics(self) -> dict:
        return {
            "stats": [
                {"label": "Delivered", "value": self._delivered},
                {"label": "Failed", "value": self._failed},
            ]
        }
