import time
import unittest

from kurier.utilities.uuidv7 import UUIDv7


class TestUUIDv7Compliance(unittest.TestCase):
    def test_version_and_variant(self):
        """Check that generated UUIDs have correct version and variant."""

        u = UUIDv7.get()

        self.assertEqual(u.version, 7, "UUID version should be 7")
        self.assertEqual(
            u.variant,
            "specified in RFC 4122",
            "UUID variant should be RFC 4122 compliant",
        )

    def test_timestamp_accuracy(self):
        """Check that the embedded timestamp is reasonably close to now."""

        now_ms = int(time.time() * 1000)
        u = UUIDv7.get()

        ts_extracted = u.int >> 80

        diff = abs(now_ms - ts_extracted)
        self.assertLess(
            diff,
            1000,
            f"UUID timestamp {ts_extracted} too far from now {now_ms}",
        )

    def test_randomness_structure(self):
        """Check that rand_a and rand_b are populated."""

        has_nonzero = False
        for _ in range(10):
            u = UUIDv7.get()
            val = u.int

            if (val & 0x3FFFFFFFFFFFFFFF) != 0:
                has_nonzero = True
                break
        self.assertTrue(has_nonzero, "Random bits seem to be empty")

    def test_ordering(self):
        """Check that UUIDs generated with significant delay are ordered."""

        u1 = UUIDv7.get()
        time.sleep(0.01)
        u2 = UUIDv7.get()
        self.assertLess(u1, u2, "UUIDs should be time-ordered")


if __name__ == "__main__":
    unittest.main()
