"""Tests for embeddings, vector search, BM25, fusion, and retrieval metrics."""

import unittest

from agentic.retrieval import (
    BM25,
    Chunk,
    HashingEmbedder,
    HybridRetriever,
    VectorStore,
    cosine,
    keyword_overlap_reranker,
    mrr,
    norm,
    normalize,
    precision_at_k,
    recall_at_k,
    reciprocal_rank_fusion,
    tokenize,
)


CORPUS = [
    Chunk(id="refund", text="Refunds are accepted within 30 days of delivery.",
          source="policy", section="Refunds"),
    Chunk(id="ship", text="Standard shipping takes three to five working days.",
          source="policy", section="Shipping"),
    Chunk(id="err", text="Error code E-4471 means the payment gateway timed out.",
          source="runbook", section="Errors"),
    Chunk(id="hr", text="Salary bands are reviewed each April by the people team.",
          source="hr", section="Comp", permissions=frozenset({"hr"})),
]


class TestVectorMath(unittest.TestCase):
    """The arithmetic from the maths lesson, verified by hand."""

    def test_cosine_of_identical_direction_is_one(self):
        # [4,8,8] is [1,2,2] scaled by 4 - same direction, so cosine 1.
        self.assertAlmostEqual(cosine((1, 2, 2), (4, 8, 8)), 1.0, places=9)

    def test_cosine_worked_example(self):
        # dot = 2+6+12 = 20, norms 3 and 7, so 20/21.
        self.assertAlmostEqual(cosine((1, 2, 2), (2, 3, 6)), 20 / 21, places=9)

    def test_orthogonal_vectors_score_zero(self):
        self.assertAlmostEqual(cosine((1, 2, 2), (-2, 1, 0)), 0.0, places=9)

    def test_norm_matches_pythagoras(self):
        self.assertAlmostEqual(norm((1, 2, 2)), 3.0, places=9)

    def test_normalize_gives_unit_length(self):
        self.assertAlmostEqual(norm(normalize((1, 2, 2))), 1.0, places=9)

    def test_cosine_handles_zero_vector_without_dividing_by_zero(self):
        self.assertEqual(cosine((0, 0, 0), (1, 2, 3)), 0.0)

    def test_embeddings_are_stable_across_calls(self):
        # Uses a hand-rolled FNV hash, not hash(), which is salted per process.
        e = HashingEmbedder(dim=32)
        self.assertEqual(e.embed("refund policy"), e.embed("refund policy"))

    def test_embeddings_are_unit_length(self):
        e = HashingEmbedder(dim=32)
        self.assertAlmostEqual(norm(e.embed("some text here")), 1.0, places=9)


class TestDenseSearch(unittest.TestCase):
    def setUp(self):
        self.store = VectorStore().add(*CORPUS)

    def test_finds_the_obvious_match(self):
        hits = self.store.search("refunds", k=2, permitted=frozenset({"hr"}))
        self.assertEqual(hits[0].chunk.id, "refund")

    def test_ranks_are_assigned_from_one(self):
        hits = self.store.search("shipping days", k=3, permitted=frozenset({"hr"}))
        self.assertEqual([h.rank for h in hits], [1, 2, 3][: len(hits)])

    def test_restricted_chunk_is_hidden_without_a_grant(self):
        hits = self.store.search("salary bands april", k=5)
        self.assertNotIn("hr", [h.chunk.id for h in hits])

    def test_restricted_chunk_is_visible_with_the_grant(self):
        hits = self.store.search("salary bands april", k=5, permitted=frozenset({"hr"}))
        self.assertIn("hr", [h.chunk.id for h in hits])

    def test_permission_filter_runs_before_ranking(self):
        # The restricted chunk must never occupy a top-k slot it would then be
        # filtered out of - post-filtering silently destroys recall.
        hits = self.store.search("salary", k=1)
        self.assertTrue(all(h.chunk.id != "hr" for h in hits))

    def test_chunk_context_prefix_is_included(self):
        c = CORPUS[0]
        self.assertIn("policy", c.with_context())
        self.assertIn("Refunds", c.with_context())


class TestBM25(unittest.TestCase):
    def setUp(self):
        self.bm = BM25().add(*CORPUS)

    def test_exact_identifier_is_found(self):
        # This is the query class dense embeddings blur and BM25 nails.
        hits = self.bm.search("E-4471", k=3, permitted=frozenset({"hr"}))
        self.assertTrue(hits)
        self.assertEqual(hits[0].chunk.id, "err")

    def test_unmatched_query_returns_nothing(self):
        self.assertEqual(self.bm.search("zebra unicorn", permitted=frozenset({"hr"})), [])

    def test_respects_permissions(self):
        hits = self.bm.search("salary bands", k=5)
        self.assertEqual([h.chunk.id for h in hits], [])


class TestFusion(unittest.TestCase):
    def test_rrf_combines_by_rank_not_score(self):
        a = Chunk(id="a", text="alpha")
        b = Chunk(id="b", text="beta")
        # Deliberately incomparable score scales: 900 vs 0.9.
        dense = [__import__("agentic.retrieval", fromlist=["Hit"]).Hit(chunk=b, score=0.9, rank=1)]
        lexical = [__import__("agentic.retrieval", fromlist=["Hit"]).Hit(chunk=a, score=900.0, rank=1)]
        fused = reciprocal_rank_fusion(dense, lexical, k=2)
        # Both ranked #1 by their own retriever, so both get equal fused weight -
        # the 900 does not dominate.
        self.assertEqual(len(fused), 2)
        self.assertAlmostEqual(fused[0].score, fused[1].score, places=9)

    def test_agreement_across_retrievers_wins(self):
        from agentic.retrieval import Hit

        a, b = Chunk(id="a", text="x"), Chunk(id="b", text="y")
        dense = [Hit(chunk=a, score=0.9, rank=1), Hit(chunk=b, score=0.8, rank=2)]
        lexical = [Hit(chunk=a, score=5.0, rank=1), Hit(chunk=b, score=4.0, rank=2)]
        fused = reciprocal_rank_fusion(dense, lexical, k=2)
        self.assertEqual(fused[0].chunk.id, "a")


class TestHybrid(unittest.TestCase):
    def setUp(self):
        self.r = HybridRetriever().add(*CORPUS)
        self.grants = frozenset({"hr"})

    def test_hybrid_finds_both_query_kinds(self):
        exact = self.r.search("E-4471", k=3, permitted=self.grants)
        self.assertEqual(exact[0].chunk.id, "err")
        fuzzy = self.r.search("money back guarantee period", k=3, permitted=self.grants)
        self.assertIn("refund", [h.chunk.id for h in fuzzy])

    def test_reranker_reorders_the_shortlist(self):
        plain = self.r.search("30 days delivery refunds", k=4, permitted=self.grants)
        reranked = self.r.search(
            "30 days delivery refunds", k=4, permitted=self.grants,
            rerank=keyword_overlap_reranker,
        )
        self.assertEqual(reranked[0].chunk.id, "refund")
        self.assertEqual(reranked[0].retriever, "reranked")
        self.assertTrue(plain)

    def test_permissions_hold_through_the_hybrid_path(self):
        hits = self.r.search("salary bands april", k=5)
        self.assertNotIn("hr", [h.chunk.id for h in hits])


class TestRetrievalMetrics(unittest.TestCase):
    def setUp(self):
        from agentic.retrieval import Hit

        self.hits = [
            Hit(chunk=CORPUS[1], score=0.9, rank=1),   # ship  - not relevant
            Hit(chunk=CORPUS[0], score=0.8, rank=2),   # refund - relevant
        ]

    def test_recall_at_k(self):
        self.assertEqual(recall_at_k(self.hits, {"refund"}), 1.0)
        self.assertEqual(recall_at_k(self.hits, {"refund", "err"}), 0.5)
        self.assertEqual(recall_at_k(self.hits, {"refund"}, k=1), 0.0)

    def test_precision_at_k(self):
        self.assertEqual(precision_at_k(self.hits, {"refund"}), 0.5)
        self.assertEqual(precision_at_k(self.hits, {"refund"}, k=1), 0.0)

    def test_mrr_reports_first_relevant_position(self):
        self.assertAlmostEqual(mrr(self.hits, {"refund"}), 0.5)
        self.assertEqual(mrr(self.hits, {"nothing"}), 0.0)

    def test_empty_relevant_set_is_vacuously_perfect(self):
        self.assertEqual(recall_at_k(self.hits, set()), 1.0)


class TestTokenize(unittest.TestCase):
    def test_lowercases_and_splits_on_punctuation(self):
        self.assertEqual(tokenize("Error E-4471: timed-out!"), ["error", "e", "4471", "timed", "out"])


if __name__ == "__main__":
    unittest.main()