import asyncio

from bleak.backends.device import BLEDevice
from bleak.backends.scanner import AdvertisementData
from pytest import MonkeyPatch

from k1link.device_plugins.xgrids_k1.ble.scanner import (
    advertisement_record,
    discovered_device,
    scan,
)


def test_advertisement_record_marks_k1_candidate() -> None:
    device = BLEDevice("TEST-UUID", "Unknown", details=None)
    advertisement = AdvertisementData(
        local_name="Lixel-K1-1234",
        manufacturer_data={123: b"\x01\x02"},
        service_data={"service": b"\xaa"},
        service_uuids=["B", "a"],
        tx_power=-4,
        rssi=-52,
        platform_data=(),
    )
    record = advertisement_record(device, advertisement)
    assert record["k1_name_candidate"] is True
    assert record["id_kind"] == "corebluetooth_uuid"
    assert record["manufacturer_data_hex"] == {"123": "0102"}
    assert record["service_data_hex"] == {"service": "aa"}
    assert record["service_uuids"] == ["B", "a"]


def test_advertisement_record_marks_synthetic_xgr_name_as_k1_candidate() -> None:
    device = BLEDevice("00000000-0000-0000-0000-000000000001", "XGR-TEST01", None)
    advertisement = AdvertisementData(
        local_name="XGR-TEST01",
        manufacturer_data={},
        service_data={},
        service_uuids=[],
        tx_power=0,
        rssi=-60,
        platform_data=(),
    )

    record = advertisement_record(device, advertisement)
    assert record["k1_name_candidate"] is True


def test_scan_retains_the_live_corebluetooth_handle(
    monkeypatch: MonkeyPatch,
) -> None:
    device = BLEDevice("LIVE-UUID", "XGR-LIVE", details=object())
    advertisement = AdvertisementData(
        local_name="XGR-LIVE",
        manufacturer_data={},
        service_data={},
        service_uuids=[],
        tx_power=0,
        rssi=-41,
        platform_data=(),
    )

    async def fake_discover(**_kwargs: object) -> dict[str, tuple[BLEDevice, AdvertisementData]]:
        return {"LIVE-UUID": (device, advertisement)}

    monkeypatch.setattr(
        "k1link.device_plugins.xgrids_k1.ble.scanner.BleakScanner.discover",
        fake_discover,
    )

    result = asyncio.run(scan(1.0))

    assert result["devices"][0]["macos_uuid"] == "LIVE-UUID"
    assert discovered_device("LIVE-UUID") is device
