import asyncio
import logging
import itertools
import urllib.parse
from typing import Optional

from maps_adv.geosmb.clients.logbroker.logbroker import LogbrokerClient
from robot.protos.crawl.compatibility.feeds_pb2 import TFeedExt
from .timing import async_time_diff

logger = logging.getLogger(__name__)


class ExtFeedLogbrokerWriter:
    def __init__(self, config: dict):
        self._client = None
        if config.get("ENABLE_EXT_FEED_WRITER", False):
            self._base_domain = config["LANDING_BASE_DOMAIN"]
            self._client = LogbrokerClient(
                host="logbroker.yandex.net",
                port=2135,
                default_source_id=b"business-urls-ext",
                tvm_self_alias=config["TVM_SELF_ALIAS"],
                tvm_destination="logbroker",
                tvm_port=urllib.parse.urlparse(config["TVM_DAEMON_URL"]).port,
            )

    async def start(self):
        if self._client:
            await self._client.start()

    async def close(self):
        if self._client:
            await self._client.stop()

    @async_time_diff
    async def write_urls(self, *, slug: Optional[str] = None, slugs: Optional[list] = None):
        if not self._client:
            return

        assert slug or slugs
        slugs = slugs or []
        if slug:
            slugs.append(slug)

        # in order to max up to 5 rps
        lb_batch_size = 5
        sleep_secs = 1
        pause_needed = False

        try:
            async with self._client.create_writer("/samovar/feeds-ext") as topic_writer:
                slug_iter = iter(slugs)
                for sliced_slugs in iter(lambda: tuple(itertools.islice(slug_iter, lb_batch_size)), ()):
                    if pause_needed:
                        await asyncio.sleep(sleep_secs)
                    pause_needed = True
                    for slug in sliced_slugs:
                        feed_ext = TFeedExt()
                        feed_ext.FeedName = "business-urls-ext"
                        feed_ext.Url = f"https://{slug}.{self._base_domain}/sitemap.xml"
                        logger.debug(f"Sending ext feed for url {feed_ext.Url}")
                        await topic_writer.write_one(feed_ext.SerializeToString())

        except Exception as ex:
            logger.error(ex)

    def write_urls_async(self, *, slug: Optional[str] = None, slugs: Optional[list] = None):
        asyncio.create_task(self.write_urls(slug=slug, slugs=slugs))
