from __future__ import annotations

import asyncio
from pathlib import Path
from typing import Any

from pytest import MonkeyPatch

import k1link.device_plugins.xgrids_k1.facade as xgrids_backend


def test_ble_scan_exposes_every_device_and_only_labels_likely_k1(
    monkeypatch: MonkeyPatch,
    tmp_path: Path,
) -> None:
    async def fake_scan(duration_seconds: float) -> dict[str, Any]:
        assert duration_seconds == 6.0
        return {
            "devices": [
                {
                    "macos_uuid": "K1-UUID",
                    "name": "XGR-TEST01",
                    "local_name": "XGR-TEST01",
                    "rssi": -51,
                    "k1_name_candidate": True,
                },
                {
                    "macos_uuid": "OTHER-UUID",
                    "name": "AirPods Pro",
                    "local_name": "AirPods Pro",
                    "rssi": -62,
                    "k1_name_candidate": False,
                },
            ]
        }

    monkeypatch.setattr(xgrids_backend, "scan", fake_scan)
    service = xgrids_backend.XgridsK1CompatibilityService(tmp_path)

    state = asyncio.run(service.scan_ble(6.0))

    assert state["selected_device_id"] is None
    assert [device["device_id"] for device in state["devices"]] == [
        "K1-UUID",
        "OTHER-UUID",
    ]
    assert [device["likely_k1"] for device in state["devices"]] == [True, False]


def test_viewer_settings_are_validated_and_exposed(tmp_path: Path) -> None:
    service = xgrids_backend.XgridsK1CompatibilityService(tmp_path)
    request = xgrids_backend.ViewerSettingsRequest(
        point_size=4.0,
        color_mode="height",
        palette="viridis",
        custom_color="#102030",
        accumulation_seconds=18,
        show_points=True,
        show_trajectory=False,
        show_grid=False,
    )

    state = service.update_viewer_settings(request)

    assert state["rerun_grpc_url"] is None
    assert state["viewer_settings"] == {
        "point_size": 4.0,
        "color_mode": "height",
        "palette": "viridis",
        "custom_color": "#102030",
        "accumulation_seconds": 18.0,
        "show_points": True,
        "show_trajectory": False,
        "show_grid": False,
        "show_detections_2d": False,
        "show_segmentation": False,
        "show_cuboids_3d": False,
    }
