# KEKS -- Python KEKS implementation
# Copyright (C) 2024-2025 Anton Rudenko <rudenko.ad@phystech.edu>
#               2024-2025 Sergey Matveev <stargrave@stargrave.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation, version 3 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program.  If not, see <http://www.gnu.org/licenses/>.

from typing import Any
from typing import Mapping
from typing import Set
from unittest import TestCase

from hypothesis import given
from hypothesis.strategies import dictionaries
from hypothesis.strategies import sets

from keks import DecodeError
from keks import dumps
from keks import loads
from tests.strategies import any_st
from tests.strategies import junk_st
from tests.strategies import mapkey_st


class TestMap(TestCase):
    @given(dictionaries(keys=mapkey_st, values=any_st, max_size=4), junk_st)
    def test_symmetric(self, test_map: Mapping[str, Any], junk: bytes):
        encoded = dumps(test_map)
        expected = (
            b"\x09" +
            b"".join(
                [
                    b"".join([dumps(key), dumps(test_map[key])])
                    for key in sorted(test_map.keys(), key=lambda x: (
                        len(x.encode("utf-8")),
                        x.encode("utf-8"),
                    ))
                ]
            ) +
            b"\x00"
        )
        self.assertSequenceEqual(encoded, expected)
        decoded, tail = loads(encoded + junk)
        self.assertEqual(decoded, test_map)
        self.assertSequenceEqual(tail, junk)

    @given(junk_st)
    def test_empty(self, junk):
        test_map = {}
        encoded = dumps(test_map) + junk
        expected = b"\x09\x00" + junk
        self.assertSequenceEqual(encoded, expected)
        decoded, tail = loads(encoded)
        self.assertEqual(decoded, test_map)
        self.assertSequenceEqual(tail, junk)

    def test_throws_when_decoding_unsorted_value_keys(self):
        encoded = b"".join((
            bytes.fromhex("09"),
            bytes.fromhex("C4"), b"key2",
            bytes.fromhex("0C8101"),
            bytes.fromhex("C4"), b"key1",
            bytes.fromhex("C6"), b"value1",
            bytes.fromhex("00"),
        ))
        with self.assertRaises(DecodeError) as err:
            loads(encoded)
        self.assertEqual(str(err.exception), "unsorted keys")

    def test_throws_when_decoding_unsorted_len_keys(self):
        encoded = b"".join((
            bytes.fromhex("09"),
            bytes.fromhex("C4"), b"key2",
            bytes.fromhex("0C8101"),
            bytes.fromhex("C3"), b"key",
            bytes.fromhex("C6"), b"value1",
            bytes.fromhex("00"),
        ))
        with self.assertRaises(DecodeError) as err:
            loads(encoded)
        self.assertEqual(str(err.exception), "unsorted keys")

    def test_throws_when_encoding_non_string_key(self):
        with self.assertRaises(ValueError) as err:
            dumps({1: "a"})
        self.assertEqual(str(err.exception), "map keys can be only strings")

    def test_throws_when_decoding_non_string_key(self):
        encoded = b"".join((
            bytes.fromhex("09"),
            bytes.fromhex("0C80C6"), b"value2",
            bytes.fromhex("00"),
        ))
        with self.assertRaises(DecodeError) as err:
            loads(encoded)
        self.assertEqual(str(err.exception), "non-string key")

    def test_throws_when_unexpected_eoc(self):
        encoded = b"".join((
            bytes.fromhex("09"),
            bytes.fromhex("C4"), b"key1",
            bytes.fromhex("00"),
            bytes.fromhex("00"),
        ))
        with self.assertRaises(DecodeError) as err:
            decoded, tail = loads(encoded)
        self.assertEqual(str(err.exception), "unexpected EOC")

    def test_throws_when_encoding_empty_str_as_key(self):
        with self.assertRaises(ValueError) as err:
            dumps({"": "a"})
        self.assertEqual(str(err.exception), "map keys can not be empty")

    def test_throws_when_decoding_empty_str_as_key(self):
        encoded = bytes.fromhex("09" + "C0" + "C0" + "00")
        with self.assertRaises(DecodeError) as err:
            decoded, tail = loads(encoded)
        self.assertEqual(str(err.exception), "empty key")


class TestSet(TestCase):
    @given(sets(mapkey_st, max_size=4), junk_st)
    def test_symmetric(self, values: Set[str], junk: bytes) -> None:
        test_map = {key: None for key in values}
        encoded = dumps(test_map)
        decoded, tail = loads(encoded + junk, sets=True)
        self.assertSetEqual(decoded, values)
        self.assertSequenceEqual(tail, junk)
        self.assertSequenceEqual(dumps(values), encoded)

    def test_non_str(self) -> None:
        with self.assertRaises(ValueError) as err:
            dumps(set((123,)))
        self.assertEqual(str(err.exception), "set can contain only strings")

    def test_sets_are_passed_through_containers(self) -> None:
        test = {"deep": [{"in map": [set(("foo", "bar"))]}]}
        encoded = dumps(test)
        decoded, tail = loads(encoded, sets=True)
        self.assertEqual(decoded, test)

    def test_equal_len_codepoints(self):
        s1 = bytes.fromhex("f1ad9bb3c2997c6dc391c2a0c2845a").decode("utf-8")
        s2 = bytes.fromhex("f1aaab9ec3adc2bcc3b4c3bec38a0cc3ac").decode("utf-8")
        encoded = dumps(set((s1, s2)))
        self.assertSequenceEqual(
            encoded.hex(),
            (b"".join((b"\x09", dumps(s1), b"\x01", dumps(s2), b"\x01", b"\x00"))).hex(),
        )
