# SPDX-FileCopyrightText: 2021 Legrandin <helderijs@gmail.com>
# SPDX-License-Identifier: BSD-2-Clause

from __future__ import annotations

from binascii import unhexlify
from typing import TYPE_CHECKING, Optional, Union

from Crypto.Random import get_random_bytes
from Crypto.Util._bytes import tobytes
from Crypto.Util._raw_api import is_buffer

from . import SHA3_256, cSHAKE128
from .cSHAKE128 import _bytepad, _encode_str, _right_encode

if TYPE_CHECKING:
    from types import ModuleType

Buffer = Union[bytes, bytearray, memoryview]


class KMAC_Hash:
    """A KMAC hash object.
    Do not instantiate directly.
    Use the :func:`new` function.
    """

    def __init__(
        self,
        data: Optional[Buffer],
        key: Buffer,
        mac_len: int,
        custom: Buffer,
        oid_variant: str,
        cshake: ModuleType,
        rate: int,
    ) -> None:
        # See https://tools.ietf.org/html/rfc8702
        self.oid = "2.16.840.1.101.3.4.2." + oid_variant
        self.digest_size = mac_len

        self._mac: Optional[bytes] = None
        self._cshake_module = cshake

        partial_newX = _bytepad(_encode_str(tobytes(key)), rate)
        self._cshake = cshake._new(partial_newX, custom, b"KMAC")

        if data:
            self._cshake.update(data)

    def update(self, data: Buffer) -> KMAC_Hash:
        """Authenticate the next chunk of message.

        Args:
            data (bytes/bytearray/memoryview): The next chunk of the message to
            authenticate.
        """

        if self._mac:
            raise TypeError("You can only call 'digest' or 'hexdigest' on this object")

        self._cshake.update(data)
        return self

    def digest(self) -> bytes:
        """Return the **binary** (non-printable) MAC tag of the message.

        :return: The MAC tag. Binary form.
        :rtype: byte string
        """

        if not self._mac:
            self._cshake.update(_right_encode(self.digest_size * 8))
            self._mac = self._cshake.read(self.digest_size)

        return self._mac

    def hexdigest(self) -> str:
        """Return the **printable** MAC tag of the message.

        :return: The MAC tag. Hexadecimal encoded.
        :rtype: string
        """

        return self.digest().hex()

    def verify(self, mac_tag: Buffer) -> None:
        """Verify that a given **binary** MAC (computed by another party)
        is valid.

        Args:
          mac_tag (bytes/bytearray/memoryview): the expected MAC of the message.

        Raises:
            ValueError: if the MAC does not match. It means that the message
                has been tampered with or that the MAC key is incorrect.
        """

        secret = get_random_bytes(16)

        mac1 = SHA3_256.new(secret + mac_tag)
        mac2 = SHA3_256.new(secret + self.digest())

        if mac1.digest() != mac2.digest():
            raise ValueError("MAC check failed")

    def hexverify(self, hex_mac_tag: str) -> None:
        """Verify that a given **printable** MAC (computed by another party)
        is valid.

        Args:
            hex_mac_tag (string): the expected MAC of the message, as a hexadecimal string.

        Raises:
            ValueError: if the MAC does not match. It means that the message
                has been tampered with or that the MAC key is incorrect.
        """

        self.verify(unhexlify(tobytes(hex_mac_tag)))

    def new(
        self,
        *,
        key: Buffer,
        data: Optional[Buffer] = None,
        mac_len: Optional[int] = None,
        custom: Buffer = b"",
    ) -> KMAC_Hash:
        """Return a new instance of a KMAC hash object.
        See :func:`new`.
        """

        if mac_len is None:
            mac_len = self.digest_size

        # The same class implements both KMAC128 and KMAC256
        if self._cshake_module is cSHAKE128:
            factory = new
        else:
            from .KMAC256 import new as factory

        return factory(key=key, data=data, mac_len=mac_len, custom=custom)


def new(*, key: Buffer, data: Optional[Buffer] = None, mac_len: int = 64, custom: Buffer = b"") -> KMAC_Hash:
    """Create a new KMAC128 object.

    Args:
        key (bytes/bytearray/memoryview):
            The key to use to compute the MAC.
            It must be at least 128 bits long (16 bytes).
        data (bytes/bytearray/memoryview):
            Optional. The very first chunk of the message to authenticate.
            It is equivalent to an early call to :meth:`KMAC_Hash.update`.
        mac_len (integer):
            Optional. The size of the authentication tag, in bytes.
            Default is 64. Minimum is 8.
        custom (bytes/bytearray/memoryview):
            Optional. A customization byte string (``S`` in SP 800-185).

    Returns:
        A :class:`KMAC_Hash` hash object
    """

    if not is_buffer(key):
        raise TypeError("You must pass a key to KMAC128")
    if len(key) < 16:
        raise ValueError("The key must be at least 128 bits long (16 bytes)")

    if mac_len < 8:
        raise ValueError("'mac_len' must be 8 bytes or more")

    return KMAC_Hash(data, key, mac_len, custom, "19", cSHAKE128, 168)
