"""Tests for setup wizard Ascend detection consistency."""

from __future__ import annotations

from sagellm.cli.commands import setup as setup_cmd


def test_detect_ascend_ready_uses_cache_framework(monkeypatch) -> None:
    class _FakeCache:
        def load_raw(self):
            return {"ascend": {"max_level": "framework"}}

    monkeypatch.setattr(setup_cmd, "_get_profile_cache_cls", lambda: _FakeCache)
    monkeypatch.setattr(setup_cmd, "check_ascend_available", lambda: (False, "fallback"))

    assert setup_cmd._detect_ascend_ready() is True


def test_detect_ascend_ready_falls_back_when_cache_unusable(monkeypatch) -> None:
    class _FakeCache:
        def load_raw(self):
            return {"ascend": {"max_level": "physical"}}

    monkeypatch.setattr(setup_cmd, "_get_profile_cache_cls", lambda: _FakeCache)
    monkeypatch.setattr(setup_cmd, "check_ascend_available", lambda: (True, "fallback"))

    assert setup_cmd._detect_ascend_ready() is True


def test_detect_ascend_ready_uses_inspector_fallback(monkeypatch) -> None:
    class _FakeCache:
        def load_raw(self):
            return {"ascend": {"max_level": "unavailable"}}

        def update(self, *_args, **_kwargs):
            return None

    class _FakeProfile:
        def is_usable(self):
            return True

    class _FakeInspector:
        def get_profile(self, include_functional=False):
            return _FakeProfile()

    monkeypatch.setattr(setup_cmd, "_get_profile_cache_cls", lambda: _FakeCache)
    monkeypatch.setattr(setup_cmd, "_get_ascend_inspector", lambda: _FakeInspector())
    monkeypatch.setattr(setup_cmd, "check_ascend_available", lambda: (False, "fallback"))
    monkeypatch.setattr(setup_cmd.shutil, "which", lambda _bin: "/usr/bin/npu-smi")

    assert setup_cmd._detect_ascend_ready() is True


def test_detect_ascend_ready_uses_hardware_fallback(monkeypatch) -> None:
    class _FakeCache:
        def load_raw(self):
            return {"ascend": {"max_level": "unavailable"}}

    class _FailInspector:
        def get_profile(self, include_functional=False):
            raise RuntimeError("runtime check failed")

    monkeypatch.setattr(setup_cmd, "_get_profile_cache_cls", lambda: _FakeCache)
    monkeypatch.setattr(setup_cmd, "_get_ascend_inspector", lambda: _FailInspector())
    monkeypatch.setattr(setup_cmd, "check_ascend_available", lambda: (False, "fallback"))
    monkeypatch.setattr(setup_cmd.shutil, "which", lambda _bin: "/usr/bin/npu-smi")

    assert setup_cmd._detect_ascend_ready() is True
