"""Packet classes for handling Quake3 RCON protocol communication."""

MAGIC = b'\xff\xff\xff\xff'
RESPONSE_HEADER = MAGIC + b'print\n'


class Request:
    """RCON request packet for sending commands to the server."""

    _password: str = ''
    _password_bytes: bytes = b''

    _rcon_prefix: bytes = b'rcon '

    __slots__ = ()

    def to_bytes(self, command: str) -> bytes:
        """Convert the request to bytes for transmission.

        Args:
            command: Command to send to the server

        Returns:
            Byte representation of the RCON request
        """
        if not self._password_bytes:
            raise ValueError('Password not set. Use Request.set_password() first.')

        return (
            MAGIC
            + self._rcon_prefix
            + self._password_bytes
            + b' '
            + command.encode()
            + b'\n'
        )

    @classmethod
    def set_password(cls, password: str) -> None:
        """Set the RCON password for all Request instances.

        Args:
            password: RCON password for authentication
        """
        cls._password = password
        cls._password_bytes = password.encode()


class ResponseFragment:
    """Response packet constants and utilities."""

    HEADER = RESPONSE_HEADER

    __slots__ = ()
