import aitop.core.gpu.factory as factory_module
from aitop.core.gpu.apple import AppleGPUMonitor
from aitop.core.gpu.factory import GPUMonitorFactory


def test_detect_vendors_on_macos_prefers_apple_monitor(monkeypatch) -> None:
    subprocess_calls: list[list[str]] = []

    def _record_subprocess_run(*args, **kwargs):  # type: ignore[no-untyped-def]
        del kwargs
        cmd = list(args[0]) if args else []
        subprocess_calls.append(cmd)
        raise AssertionError("macOS path should not invoke Linux subprocess probes")

    monkeypatch.setattr(factory_module.platform, "system", lambda: "Darwin")
    monkeypatch.setattr(
        factory_module.shutil,
        "which",
        lambda name: "/usr/sbin/system_profiler" if name == "system_profiler" else None,
    )
    monkeypatch.setattr(factory_module.subprocess, "run", _record_subprocess_run)

    vendors = GPUMonitorFactory.detect_vendors()

    assert vendors == ["apple"]
    assert subprocess_calls == []


def test_detect_dependency_warnings_on_macos_without_system_profiler(
    monkeypatch,
) -> None:
    monkeypatch.delenv("AITOP_ENABLE_MACOS_POWERMETRICS", raising=False)
    monkeypatch.setattr(factory_module.platform, "system", lambda: "Darwin")
    monkeypatch.setattr(factory_module.shutil, "which", lambda _name: None)

    warnings = GPUMonitorFactory.detect_dependency_warnings()

    assert any("system_profiler" in warning for warning in warnings)
    assert not any("powermetrics" in warning for warning in warnings)


def test_detect_dependency_warnings_on_macos_with_powermetrics_opt_in(
    monkeypatch,
) -> None:
    monkeypatch.setenv("AITOP_ENABLE_MACOS_POWERMETRICS", "1")
    monkeypatch.setattr(factory_module.platform, "system", lambda: "Darwin")
    monkeypatch.setattr(factory_module.shutil, "which", lambda _name: None)

    warnings = GPUMonitorFactory.detect_dependency_warnings()

    assert any("powermetrics" in warning for warning in warnings)


def test_create_monitors_includes_apple_monitor(monkeypatch) -> None:
    monkeypatch.setattr(
        GPUMonitorFactory, "detect_vendors", staticmethod(lambda: ["apple"])
    )

    monitors = GPUMonitorFactory.create_monitors()

    assert len(monitors) == 1
    assert isinstance(monitors[0], AppleGPUMonitor)
