"""Tests for context retrieval engine."""
import json
import pytest
from greymatter_core.db import SQLiteDatabase
from greymatter_core.standards import StandardsManager
from greymatter_core.documents import DocumentStore
from greymatter_core.patterns import PatternManager
from greymatter_core.context import ContextEngine


@pytest.fixture
def db():
    database = SQLiteDatabase(":memory:")
    yield database
    database.close()


@pytest.fixture
def engine(db):
    standards = StandardsManager(db)
    standards.seed_defaults()
    docs = DocumentStore(db)
    patterns = PatternManager(db)
    return ContextEngine(db, docs, standards, patterns)


def test_build_session_context(engine):
    ctx = engine.build_session_context()
    assert "quality_standards" in ctx
    assert "recent_context" in ctx
    assert "active_patterns" in ctx
    assert len(ctx["quality_standards"]) > 0


def test_context_includes_standards_as_json(engine):
    ctx = engine.build_session_context()
    # Standards should be parseable JSON
    parsed = json.loads(ctx["quality_standards"])
    assert isinstance(parsed, list)
    assert all("rule" in s for s in parsed)


def test_context_includes_recent_documents(engine):
    docs = DocumentStore(engine.db)
    docs.create(doc_type="session_log", title="Today", content="Work done", project="greymatter")
    ctx = engine.build_session_context(project="greymatter")
    assert len(ctx["recent_context"]) > 0


def test_context_respects_token_budget(engine):
    docs = DocumentStore(engine.db)
    for i in range(20):
        docs.create(
            doc_type="session_log", title=f"Session {i}",
            content="word " * 500, project="greymatter",
        )
    ctx = engine.build_session_context(project="greymatter", max_tokens=2000)
    # Should not include all 20 docs
    assert len(ctx["recent_context"]) < 20


def test_record_and_evaluate(engine):
    engine.record_request(session_id="s-1", query="load context", doc_ids=["doc-1"], tokens=500)
    engine.evaluate_relevance(1, score=0.8)
    # No assertion needed beyond no errors -- the data is tracked
