from granule.llm.enrich import enrich_atoms
from granule.models.core import SemanticAtom
from granule.process.jit_llm import emit_atoms_from_chunk
from granule.llm import base as llm_base
from granule.config import settings

class FakeProvider:
    def complete(self, req):  # noqa: D401
        from granule.llm.base import LLMResponse
        return LLMResponse(text='{"summary":"Short","difficulty":2,"questions":["Q1?"]}')
    def stream(self, req):
        yield "partial"

def test_enrich_atoms_disabled_returns_empty(monkeypatch):
    monkeypatch.setattr(settings, "openai_api_key", None)
    atom = SemanticAtom(kind="definition", text="Test text")
    out = enrich_atoms([atom])
    assert out == []

def test_enrich_atoms_enabled_uses_provider(monkeypatch):
    monkeypatch.setattr(settings, "openai_api_key", "sk-test")
    monkeypatch.setattr(llm_base, "get_provider", lambda name: FakeProvider())
    atom = SemanticAtom(kind="definition", text="Text body")
    out = enrich_atoms([atom])
    assert len(out) == 1
    assert out[0]["raw"].startswith("{")

def test_emit_atoms_from_chunk_injects_enriched(monkeypatch):
    monkeypatch.setattr(settings, "openai_api_key", "sk-test")
    monkeypatch.setattr(llm_base, "get_provider", lambda name: FakeProvider())
    result = emit_atoms_from_chunk("Some chunk of content", "definition")
    assert isinstance(result, list) and result
    assert "_enriched" in result[0]
    assert "raw" in result[0]["_enriched"]
