"""Tests for pybyd._crypto.aes."""

from __future__ import annotations

import pytest

from pybyd._crypto.aes import aes_decrypt_utf8, aes_encrypt_hex
from pybyd.exceptions import BydCryptoError

TRANSPORT_KEY = "9F29BE3E6254AF2C354F265B17C0CDD3"


class TestAesEncryptHex:
    def test_known_vector(self) -> None:
        result = aes_encrypt_hex("test", TRANSPORT_KEY)
        assert result == "3E1930B563F77A1072124DD9BB824472"

    def test_json_payload(self) -> None:
        result = aes_encrypt_hex('{"hello":"world"}', TRANSPORT_KEY)
        assert result == "D1CC482064CC0E1D49517F43D201DD9D2114BC2264DDBC6DBBB1E4074F30B3B0"

    def test_always_uppercase(self) -> None:
        result = aes_encrypt_hex("anything", TRANSPORT_KEY)
        assert result == result.upper()

    def test_output_is_hex(self) -> None:
        result = aes_encrypt_hex("data", TRANSPORT_KEY)
        int(result, 16)  # should not raise

    def test_bad_key_raises(self) -> None:
        with pytest.raises(BydCryptoError):
            aes_encrypt_hex("test", "ZZZZ")


class TestAesDecryptUtf8:
    def test_roundtrip(self) -> None:
        plaintext = '{"hello":"world","number":42}'
        encrypted = aes_encrypt_hex(plaintext, TRANSPORT_KEY)
        decrypted = aes_decrypt_utf8(encrypted, TRANSPORT_KEY)
        assert decrypted == plaintext

    def test_known_decrypt(self) -> None:
        decrypted = aes_decrypt_utf8("3E1930B563F77A1072124DD9BB824472", TRANSPORT_KEY)
        assert decrypted == "test"

    def test_bad_ciphertext_raises(self) -> None:
        with pytest.raises(BydCryptoError):
            aes_decrypt_utf8("00" * 15, TRANSPORT_KEY)  # not a valid block
