import numpy as np

from src.repositories.actionBar import itemIcons as iconsModule
from src.wiki.items import itemName


def test_item_names_from_database():
    assert itemName(266) == 'health potion'
    assert itemName(3031) == 'gold coin'
    assert itemName(8829) == 'food matrix crystal'
    assert itemName(99999999) is None


def test_existing_icon_short_circuits(tmp_path, mocker):
    path = tmp_path / '266.png'
    path.write_bytes(b'x')
    mocker.patch.object(iconsModule, '_itemsPath', tmp_path)

    assert iconsModule.ensureItemIcon(266) == path


def test_unknown_item_returns_none(tmp_path, mocker):
    mocker.patch.object(iconsModule, '_itemsPath', tmp_path)

    assert iconsModule.ensureItemIcon(99999999) is None


def test_fetch_writes_icon_and_registers_name(tmp_path, mocker):
    mocker.patch.object(iconsModule, '_itemsPath', tmp_path)

    class _Response:
        def __enter__(self):
            return self

        def __exit__(self, *args):
            return False

        def read(self):
            image = np.full((32, 32, 3), 200, dtype=np.uint8)
            ok, buffer = iconsModule.cv2.imencode('.png', image)
            return buffer.tobytes()

    mocker.patch.object(
        iconsModule.urllib.request, 'urlopen', return_value=_Response())

    path = iconsModule.ensureItemIcon(3031)

    assert path == tmp_path / '3031.png'
    assert path.exists()
    assert iconsModule.SLOT_ITEMS[3031] == 'gold coin'
