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.error import NanoHandlerError
from clarabot_nano_common.common.protocol.errors import (
    NANO_REQUEST_ERROR_HANDLER_BAD_REQUEST,
    NANO_REQUEST_ERROR_HANDLER_DENIED,
    NANO_REQUEST_ERROR_HANDLER_TARGET_NOT_FOUND,
    NANO_REQUEST_ERROR_LOCKED_PATH,
)
from clarabot_nano_common.common.protocol.request import NanoRequestContext
from clarabot_nano_common.server.base.config import ServerConfig
from clarabot_nano_common.server.base.handler.base import ServerHandleHelper
from clarabot_nano_common.utility.file import path_stat_differs
from clarabot_nano_common.utility.path.validate import ValidationError

from clarabot_nano.common.filesystem.operation.delete import DeleteOperation
from clarabot_nano.common.filesystem.tx_queue import TokenLockError
from clarabot_nano.common.request.server_fstx import NanoFilesystemDeleteRequest
from clarabot_nano.server.fstx.handler.base import AbstractFilesystemTransactorNanoHandler


class DeleteSystemHandler(AbstractFilesystemTransactorNanoHandler):
    EXECUTION_STATE_CAN_CONFLICT = False  # cacheable and request_key are constant, no conflict is possible

    HANDLER_KEY = NanoFilesystemDeleteRequest.TYPE_KEY

    def __init__(self, helper: ServerHandleHelper, extracted_config: ServerConfig, context: dict, payload: dict):
        AbstractFilesystemTransactorNanoHandler.__init__(self, helper, extracted_config, context, payload)
        if not isinstance(self.payload.get(NanoFilesystemDeleteRequest.PATH), str):
            raise NanoHandlerError(NANO_REQUEST_ERROR_HANDLER_BAD_REQUEST, "Missing path", self)
        if not self.can_write_drive():  # anonymous is denied by mutation-id requirement
            raise NanoHandlerError(NANO_REQUEST_ERROR_HANDLER_DENIED, "No permission", self)
        self.path = None

    async def _create_request_key(self, secure: bool = False) -> Tuple[bool, Optional[list], int]:
        return self._secure_request_key(False, None, 1) if secure else False, None, 1

    async def _execute_initial(self) -> dict:
        d = await AbstractFilesystemTransactorNanoHandler._execute_initial(self)
        try:
            # The target is resolved only up to the last part by .new_path(), this makes it possible to remove symlinks.
            # NOTE: No normalization on the last name, because it is expected to be provided as-is and exist for delete.
            self.path, s = self.chroot.new_path(self.payload[NanoFilesystemDeleteRequest.PATH])
            if s is None:
                raise NanoHandlerError(NANO_REQUEST_ERROR_HANDLER_TARGET_NOT_FOUND, "Not found", self)
            async with self.helper.fstx_queue.wait_ready(
                DeleteOperation(self.context[NanoRequestContext.ACCOUNT_ID], self.path.as_posix())
            ) as submitter:
                # Final check before execution. This can fail if contesting operations have changed the filesystem.
                path2, s2 = self.chroot.new_path(self.payload[NanoFilesystemDeleteRequest.PATH])
                if s2 is None:  # Prioritize having more accurate error than the generic contest-fail.
                    raise NanoHandlerError(NANO_REQUEST_ERROR_HANDLER_TARGET_NOT_FOUND, "Not found", self)
                if path_stat_differs(self.path, s, path2, s2):
                    raise ValidationError("Depending paths are contested")
                await submitter()  # TODO: timeout
        except ValidationError as e:
            raise NanoHandlerError(
                NANO_REQUEST_ERROR_HANDLER_BAD_REQUEST, "Invalid path", self, maybe_conflict=True
            ) from e
        except OSError as e:
            raise NanoHandlerError(
                NANO_REQUEST_ERROR_HANDLER_BAD_REQUEST, "Unresolved path", self, maybe_conflict=True
            ) from e
        except TokenLockError as e:
            raise NanoHandlerError(NANO_REQUEST_ERROR_LOCKED_PATH, "Locked path", self) from e
        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"Delete {log_escape_str(self.path)}"

    def build_error_message(self, buf: StringIO) -> None:
        buf.write("Delete ")
        buf.write(log_escape_str(self.payload.get(NanoFilesystemDeleteRequest.PATH)))
        buf.write(" in ")
        buf.write(log_escape_str(self.get_drive_root_for_error_message()))
