from __future__ import annotations

import eightmem.llm.ollama as ollama
from eightmem.llm.ollama import extract_text


def test_extract_text_prefers_response():
    text, source = extract_text({"response": "ok", "thinking": "fallback"})
    assert text == "ok"
    assert source == "response"


def test_extract_text_uses_message_content():
    text, source = extract_text({"message": {"content": "from message"}})
    assert text == "from message"
    assert source == "message.content"


def test_extract_text_falls_back_to_thinking():
    text, source = extract_text({"response": "", "thinking": "reasoning output"})
    assert text == "reasoning output"
    assert source == "thinking"


def test_check_backend_success(monkeypatch):
    class _Resp:
        def __enter__(self):
            return self

        def __exit__(self, exc_type, exc, tb):
            return False

        def read(self):
            return b'{"models":[]}'

    monkeypatch.setattr(ollama, "urlopen", lambda req, timeout=2: _Resp())

    ok, error = ollama.check_backend()

    assert ok is True
    assert error is None


def test_check_backend_failure(monkeypatch):
    from urllib.error import URLError

    monkeypatch.setattr(ollama, "urlopen", lambda req, timeout=2: (_ for _ in ()).throw(URLError("down")))

    ok, error = ollama.check_backend()

    assert ok is False
    assert "Ollama request failed" in error
