"""Tests for v0.62.0: C1 (3-tier routing), C2 (ResponseCache), C3 (MiniJudge v3 retrain)."""
from llm_guard import AgentGuard


# ── C1: 3-tier routing ────────────────────────────────────────────────────────

def test_3tier_routing_config():
    g = AgentGuard()
    g.enable_3tier_routing(low_threshold=0.2, high_threshold=0.8)
    assert g._3tier_routing_enabled is True
    assert g._3tier_low_threshold == 0.2
    assert g._3tier_high_threshold == 0.8
    assert g._tier2_scorer is None


def test_3tier_routing_accepts_tier2_scorer():
    from llm_guard import RetrievalGroundingVerifier
    g = AgentGuard()
    v = RetrievalGroundingVerifier()
    g.enable_3tier_routing(tier2_scorer=v)
    assert g._tier2_scorer is v


# ── C2: ResponseCache ─────────────────────────────────────────────────────────

def test_response_cache_miss_then_hit(tmp_path):
    from llm_guard import ResponseCache
    cache = ResponseCache(db_path=str(tmp_path / "test.db"))
    key = cache.make_key("What is Paris?", "Paris is in France.")
    assert cache.get(key) is None  # miss
    cache.put(key, {"risk": 0.1})
    result = cache.get(key)
    assert result is not None
    assert result["risk"] == 0.1


def test_response_cache_ttl_expiry(tmp_path):
    import time
    from llm_guard import ResponseCache
    cache = ResponseCache(db_path=str(tmp_path / "test.db"), ttl_seconds=1)
    key = cache.make_key("q", "a")
    cache.put(key, {"risk": 0.5})
    time.sleep(1.1)
    assert cache.get(key) is None


def test_response_cache_stats(tmp_path):
    from llm_guard import ResponseCache
    cache = ResponseCache(db_path=str(tmp_path / "test.db"))
    key = cache.make_key("q", "a")
    cache.put(key, {"risk": 0.2})
    cache.get(key)        # hit
    cache.get("missing")  # miss
    s = cache.stats()
    assert s["hits"] == 1
    assert s["misses"] == 1


# ── C3: MiniJudge v3 retrain script ──────────────────────────────────────────

def test_minijudge_v3_retrain_script_exists():
    import os
    path = "/Users/amajumder/Downloads/my research/QPPG/experiments/exp_minijudge_v3_retrain.py"
    assert os.path.exists(path)


def test_response_cache_in_memory():
    from llm_guard import ResponseCache
    cache = ResponseCache()  # default = :memory:
    key = cache.make_key("hello", "world")
    cache.put(key, {"score": 0.7})
    assert cache.get(key) == {"score": 0.7}
