import pytest
import torch

from pallet.devices import device_metadata, pinned_cuda_metadata, resolve_device


def test_uuid_resolves_torch_index_independent_of_smi_order(monkeypatch):
    monkeypatch.setattr('pallet.devices.cuda_devices', lambda: [
        {'device': 'cuda:0', 'cuda_index': 0, 'uuid': '09ed84c8-4dee-efc0-dc1d-deda5177e4e8', 'name': 'Ada', 'total_memory_bytes': 24},
        {'device': 'cuda:2', 'cuda_index': 2, 'uuid': '3ce8e1e7-efb2-80a6-de52-75da2f9fa259', 'name': 'RTX 3090', 'total_memory_bytes': 24},
    ])
    assert resolve_device('GPU-3ce8e1e7') == torch.device('cuda:2')
    assert device_metadata('09ed84c8')['name'] == 'Ada'
    with pytest.raises(ValueError, match='matched 0'):
        resolve_device('deadbeef')


def test_assistant_accepts_exact_uuid_with_generic_driver_name(monkeypatch):
    uuid = '09ed84c8-4dee-efc0-dc1d-deda5177e4e8'
    monkeypatch.setattr('pallet.devices.cuda_devices', lambda: [
        {'device': 'cuda:0', 'cuda_index': 0, 'uuid': uuid,
         'name': 'NVIDIA Graphics Device', 'total_memory_bytes': 24 * 2**30}])
    assert pinned_cuda_metadata('GPU-' + uuid)['uuid'] == uuid
    assert pinned_cuda_metadata(uuid)['name'] == 'NVIDIA Graphics Device'
    with pytest.raises(ValueError, match='matched 0'):
        pinned_cuda_metadata('GPU-3ce8e1e7-efb2-80a6-de52-75da2f9fa259')


@pytest.mark.parametrize('device', ['cpu', 'cuda:0', 'cuda', '09ed84c8'])
def test_assistant_rejects_unpinned_device_selection(device):
    with pytest.raises(ValueError, match='full GPU UUID'):
        pinned_cuda_metadata(device)


def test_assistant_rejects_resolved_uuid_mismatch(monkeypatch):
    monkeypatch.setattr('pallet.devices.device_metadata', lambda _: {'uuid': 'different'})
    with pytest.raises(ValueError, match='differs'):
        pinned_cuda_metadata('GPU-09ed84c8-4dee-efc0-dc1d-deda5177e4e8')
