import os
from typing import Tuple, Optional

from clarabot_nano.common.handler.base import NanoHandlerError, MaybeConflictNanoHandlerError
from clarabot_nano.common.protocol.errors import (
    NANO_REQUEST_ERROR_HANDLER_BAD_REQUEST,
    NANO_REQUEST_ERROR_HANDLER_DENIED,
)
from clarabot_nano.common.protocol.request import NanoRequestContext
from clarabot_nano.common.protocol.response import NanoBaseResponse
from clarabot_nano.common.request.server_fstx import NanoFilesystemMoveRequest
from clarabot_nano.server.base.config import ServerConfig
from clarabot_nano.server.base.handler.base import ServerHandleHelper
from clarabot_nano.server.fstx.filesystem.operation.rename import RenameOperation
from clarabot_nano.server.fstx.handler.base import AbstractFilesystemTransactorNanoHandler
from clarabot_nano.utility.path.validate import ValidationError


class NanoFilesystemMoveResponse(NanoBaseResponse):
    NORMALIZED_NAME = "norm_name"  # may be different from the input name due to normalization


class MoveSystemHandler(AbstractFilesystemTransactorNanoHandler):
    HANDLER_KEY = NanoFilesystemMoveRequest.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(NanoFilesystemMoveRequest.SRC_PATH), str):
            raise NanoHandlerError(NANO_REQUEST_ERROR_HANDLER_BAD_REQUEST, "Source-path is missing", self.context)
        if not isinstance(self.payload.get(NanoFilesystemMoveRequest.NEW_PATH), str):
            raise NanoHandlerError(NANO_REQUEST_ERROR_HANDLER_BAD_REQUEST, "New-path is missing", self.context)
        if not self.can_write_drive():  # anonymous is denied by mutation-id requirement
            raise NanoHandlerError(
                NANO_REQUEST_ERROR_HANDLER_DENIED,
                f"No permission to move {self.payload.get(NanoFilesystemMoveRequest.SRC_PATH)}",
                self.context,
            )
        self.src_path = None
        self.new_path = None

    async def _create_request_key(self) -> Tuple[bool, Optional[list], int]:
        return False, None, 1

    async def _execute_initial(self) -> dict:
        d = await AbstractFilesystemTransactorNanoHandler._execute_initial(self)
        try:
            self.src_path = self.chroot.path(self.payload[NanoFilesystemMoveRequest.SRC_PATH])
            self.new_path = self.chroot.new_path(
                self.payload[NanoFilesystemMoveRequest.NEW_PATH],
                name_preprocess_fn=self.extracted_config.normalize_remote_path,
            )
            if self.new_path.exists() and not os.path.samefile(self.src_path, self.new_path):
                raise FileExistsError()
            async with self.helper.fstx_queue.wait_ready(
                RenameOperation(
                    self.context[NanoRequestContext.ACCOUNT_ID], self.src_path.as_posix(), self.new_path.as_posix()
                )
            ) as submitter:
                # Final check before execution. This can fail if contesting operations have changed the filesystem.
                if self.src_path != self.chroot.path(
                    self.payload[NanoFilesystemMoveRequest.SRC_PATH]
                ) or self.new_path != self.chroot.new_path(
                    self.payload[NanoFilesystemMoveRequest.NEW_PATH],
                    name_preprocess_fn=self.extracted_config.normalize_remote_path,
                ):
                    raise ValidationError("Depending paths are contested")
                if self.new_path.exists() and not os.path.samefile(self.src_path, self.new_path):
                    raise FileExistsError()
                await submitter()  # TODO: timeout
                # NOTE: Moving a file can still facilitate a diversion-attack. Imagine renaming an "rm" executable
                # to "cat" for example.
                self._set_remote_file_security(self.new_path)
        except (OSError, ValidationError) as e:
            raise MaybeConflictNanoHandlerError(
                NANO_REQUEST_ERROR_HANDLER_BAD_REQUEST,
                f"Move failed {self.payload.get(NanoFilesystemMoveRequest.SRC_PATH)} "
                f"to {self.payload.get(NanoFilesystemMoveRequest.NEW_PATH)}",
                self.context,
            ) from e
        d[NanoFilesystemMoveResponse.NORMALIZED_NAME] = self.new_path.name
        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.context)

    def _log_message(self) -> str:
        return f"Moved {self.src_path} to {self.new_path}"
