import logging
from io import StringIO
from typing import Tuple, Optional

from clarabot_nano_common.common.error import log_escape_str
from clarabot_nano_common.common.handler.base import NanoHandlerError
from clarabot_nano_common.common.protocol.errors import NANO_REQUEST_ERROR_HANDLER_BAD_REQUEST
from clarabot_nano_common.common.protocol.request import NanoRequestContext
from clarabot_nano_common.common.protocol.response import NanoBaseResponse

from clarabot_nano.common.request.gateway import AdminLogReadRequest
from clarabot_nano.gateway.config import GatewayConfig
from clarabot_nano.gateway.handler.base import AbstractNanoGatewayHandler
from clarabot_nano.gateway.state.gateway import GatewayState


class LogReadResponse(NanoBaseResponse):
    BACK = "bck"


class AdminLogReadHandler(AbstractNanoGatewayHandler):
    REQUIRES_OWNER_IDENTITY = True
    REQUIRES_ADMIN_SESSION = True
    EXECUTION_STATE_CAN_CONFLICT = False  # cacheable and request_key are constant, no conflict is possible
    HANDLER_KEY = AdminLogReadRequest.TYPE_KEY
    SUCCESS_LOG_LEVEL = logging.DEBUG  # do not log this normally to avoid a feedback loop

    def __init__(self, helper: GatewayState, extracted_config: GatewayConfig, context: dict, payload: dict):
        AbstractNanoGatewayHandler.__init__(self, helper, extracted_config, context, payload)
        self.admin_session = self.payload.get(AdminLogReadRequest.ADMIN_SESSION)
        self.name = self.payload.get(AdminLogReadRequest.NAME)
        if not isinstance(self.name, str):
            raise NanoHandlerError(NANO_REQUEST_ERROR_HANDLER_BAD_REQUEST, "Invalid logger name", self)

    async def _create_request_key(self, secure: bool = False) -> Tuple[bool, Optional[list], int]:
        try:
            reader_session = self.helper.log_readers.check_reader(self.admin_session, self.name)
        except KeyError:
            raise NanoHandlerError(NANO_REQUEST_ERROR_HANDLER_BAD_REQUEST, "Not found", self)
        r = (False, [self.HANDLER_KEY, self.admin_session, reader_session], 1)
        if secure:
            return self._secure_request_key(*r)
        return r

    async def _execute_initial(self) -> dict:
        d = await AbstractNanoGatewayHandler._execute_initial(self)
        d[LogReadResponse.BACK] = await self.helper.log_readers.read(self.admin_session, self.name, forward=False)
        return d

    async def _execute_part(self, part: int, s_hmac_start_part: Optional[int]) -> dict:  # pragma: no cover
        raise NanoHandlerError(NANO_REQUEST_ERROR_HANDLER_BAD_REQUEST, "Part request is invalid", self)

    def _log_message(self) -> str:
        return f"Read logs {log_escape_str(self.name)} session {log_escape_str(self.admin_session)}"

    def build_error_message(self, buf: StringIO) -> None:
        buf.write("Read logs ")
        buf.write(log_escape_str(self.payload.get(AdminLogReadRequest.NAME)))
        if self.context.get(NanoRequestContext.ADMIN_SESSION_TTL) is not None:
            buf.write(" session ")
            buf.write(log_escape_str(self.payload.get(AdminLogReadRequest.ADMIN_SESSION)))
