import pytest

from colored.exceptions import InvalidHexColor
from colored.hexadecimal import Hex
from colored.library import Library

HEX_NEAREST: dict[str, tuple[str, ...]] = {
    '1':  ('#7f0000', '#800000', '#810000'),
    '2':  ('#007f00', '#008000', '#008100'),
    '4':  ('#00007f', '#000080', '#000081'),
    '10': ('#00fe00', '#00ff00', '#01ff00'),
    '12': ('#0000fe', '#0000ff', '#0100ff'),
    '14': ('#00feff', '#00ffff', '#00fffe'),
}


@pytest.mark.parametrize("expected,hex_codes", HEX_NEAREST.items())
def test_hex_nearest_match(expected: str, hex_codes: tuple[str, ...]) -> None:
    hexad = Hex()
    for hex_code in hex_codes:
        nearest = hexad.find(hex_code)
        assert Library.HEX_COLORS[nearest] == Library.HEX_COLORS[expected]


def test_hex_invalid_format_raises() -> None:
    hexad = Hex()
    for invalid in ('#FF', '#AABBCCDD', 'red', ''):
        with pytest.raises(InvalidHexColor):
            hexad.find(invalid)


def test_hex_shorthand_expansion() -> None:
    hexad = Hex()
    for r in range(0, 0xF):
        for g in range(0, 0xF):
            for b in range(0, 0xF):
                short = '#%x%x%x' % (r, g, b)
                long = '#%x%x%x%x%x%x' % (r, r, g, g, b, b)
                assert hexad.find(long) == hexad.find(short)
