import safe_radix32

from clarabot_nano.core.config.update.base import AbstractRemoteConfigUpdateHandler
from clarabot_nano.core.config.utility import block_name_from_config_format


class VerifyRoomBlocks(AbstractRemoteConfigUpdateHandler):
    HANDLER_KEY = "verify-room-blocks"

    def _execute(self, data: dict):
        room_id = data.get("room_id")
        if not isinstance(room_id, str) or not room_id or safe_radix32.ALPHABET_RE.match(room_id) is None:
            raise Exception("Room id is missing or invalid")
        room_blocks = data.get("room_blocks")
        if not isinstance(room_blocks, list):
            raise Exception("Room block(s) is missing or invalid")
        for room_block in room_blocks:
            if not block_name_from_config_format(room_block):
                raise Exception("Format of room block is invalid")
        self._c.setdefault("room_blocks", {})[room_id] = room_blocks

    def _describe_change(self, old_config: dict, new_config: dict, data: dict) -> str:
        return f"Config verification of room {data.get('room_id')!r} updated"
