"""Issue #269 + #271: provenance + recency_weight."""
import pytest; pytest.importorskip("fastapi")
from contextlib import contextmanager
from unittest.mock import AsyncMock, MagicMock, patch

@contextmanager
def _c(**ov):
    mp = MagicMock(); mp.config = MagicMock(); mp.config.owner_id = "owner-1"
    mp.storage = MagicMock(); mp.storage.initialize = AsyncMock(); mp.storage.close = AsyncMock()
    mp.storage.count_claims = AsyncMock(return_value=10)
    mp.storage.get_claim = AsyncMock(return_value=MagicMock(id="m1", subject="u", predicate="l", object_value="c", confidence=0.9))
    mp.storage.get_changelog = AsyncMock(return_value=[])
    mp.storage.get_provenance = AsyncMock(return_value=ov.get("prov", [MagicMock(id="p1", episode_event_id="e1")]))
    mp.storage.get_claims_by_subject = AsyncMock(return_value=[])
    mp.storage.get_claims_by_entity = AsyncMock(return_value=[])
    mp.storage.log_changelog = AsyncMock()
    mp.storage.delete_claim = AsyncMock()
    mp.storage.get_cornerstones = AsyncMock(return_value=[])
    mp.storage.get_category_counts = AsyncMock(return_value=[])
    mp.remember = AsyncMock(return_value=MagicMock(session_id="s1", claims_stored=1, errors=[], ok=True))
    with patch("cortex.api.plugin.CortexPlugin") as MC:
        from cortex.api.http_server import create_app
        from fastapi.testclient import TestClient
        app = create_app(api_key="test"); MC.return_value = mp
        with TestClient(app, raise_server_exceptions=True) as tc:
            yield tc, mp

class TestProvenance:
    def test_field(self):
        with _c() as (tc, _):
            d = tc.get("/api/v1/memories/m1", headers={"X-API-Key": "test"}).json()
        assert "provenance" in d
    def test_called(self):
        with _c() as (tc, mp):
            tc.get("/api/v1/memories/m1", headers={"X-API-Key": "test"})
        mp.storage.get_provenance.assert_called_once()

class TestRecency:
    def test_default(self):
        from cortex.config import CortexConfig
        assert CortexConfig().retrieval_recency_weight == 0.0
    def test_set(self):
        from cortex.config import CortexConfig
        assert CortexConfig(retrieval_recency_weight=0.2).retrieval_recency_weight == 0.2
