"""Shared fixtures for the WildEdge SDK test suite."""

import sys
from types import SimpleNamespace
from unittest.mock import MagicMock, patch

import pytest

from wildedge.client import WildEdge
from wildedge.model import ModelInfo
from wildedge.platforms.device_info import DeviceInfo


@pytest.fixture(autouse=True)
def reset_hardware_sampler():
    yield
    from wildedge.platforms import stop_sampler

    stop_sampler()


PLATFORM_MARKS = {
    "requires_linux": "linux",
    "requires_macos": "darwin",
    "requires_windows": "win32",
}


def pytest_collection_modifyitems(items):
    for item in items:
        for mark_name, required_platform in PLATFORM_MARKS.items():
            if item.get_closest_marker(mark_name) and sys.platform != required_platform:
                item.add_marker(
                    pytest.mark.skip(reason=f"requires {required_platform}")
                )
                break


@pytest.fixture
def device_info():
    return DeviceInfo(
        app_version="1.0.0",
        device_id="test-device-id",
        device_type="linux",
        os_version="test-os",
        locale="en_US",
        timezone="UTC",
        cpu_arch="x86_64",
        cpu_cores=4,
        ram_total_bytes=8 * 1024**3,
        disk_total_bytes=256 * 1024**3,
        accelerators=["cpu"],
        gpu_name=None,
    )


@pytest.fixture
def model_info():
    return ModelInfo(
        model_name="test-model",
        model_version="1.0.0",
        model_source="local",
        model_format="onnx",
        model_family="test",
        quantization="int8",
    )


@pytest.fixture
def publish_spy():
    events = []

    def publish(event):
        events.append(event)

    publish.events = events
    return publish


@pytest.fixture
def dummy_handle():
    handle = SimpleNamespace(
        model_id="model-1",
        track_download=MagicMock(),
        track_load=MagicMock(),
        track_unload=MagicMock(),
        track_inference=MagicMock(),
        track_error=MagicMock(),
    )
    return handle


@pytest.fixture
def client_with_stubbed_runtime():
    with (
        patch("wildedge.client.detect_device", return_value=DeviceInfo("id", "linux")),
        patch("wildedge.client.Transmitter"),
        patch("wildedge.client.Consumer"),
    ):
        client = WildEdge(
            dsn="https://secret@ingest.wildedge.dev/key",
            sampling_interval_s=None,
        )
    return client
