import abc
import json
import os
import time
import uuid

from saas.protos.rtyserver_pb2 import TMessage
from saas.tools.devops.canary.writer.configs import ToolConfig
from saas.tools.devops.canary.writer.service import SaasServiceWrapper


class DeliveryProcessor(metaclass=abc.ABCMeta):
    ASYNC_INIT_REQUIRED = False
    _DOCUMENT_TTL_MINUTES = 60 * 48

    def __init__(self, config: ToolConfig, service: SaasServiceWrapper, stream_id: int) -> None:
        self._config: ToolConfig = config
        self._service: SaasServiceWrapper = service
        self._stream_id: int = stream_id
        self._hostname: str = os.environ.get('HOSTNAME')

    async def async_init(self) -> None:
        raise NotImplementedError

    def generate_document(self, url: str) -> TMessage:
        proto_message = TMessage()
        proto_message.MessageType = TMessage.MODIFY_DOCUMENT
        proto_message.Document.Url = f'{self._hostname}_{url}' if self._hostname else url
        proto_message.Document.Body = json.dumps({'payload': uuid.uuid4().hex})
        proto_message.Document.DeadlineMinutesUTC = int(time.time() / 60) + self._DOCUMENT_TTL_MINUTES
        proto_message.Document.StreamId = self._stream_id
        return proto_message

    @abc.abstractmethod
    async def send_document(self, document: TMessage) -> None:
        raise NotImplementedError
