import json
import unittest
from pathlib import Path
from retrieval import bm25, ranking, hits_at

class RetrievalTests(unittest.TestCase):
    def test_exact_match_wins(self):
        self.assertGreater(bm25(['429'], [['429'], ['404']])[0], 0)
        self.assertEqual(bm25(['429'], [['429'], ['404']])[1], 0)
    def test_empty_inputs(self):
        self.assertEqual(bm25([], [['a']]), [0.0])
        self.assertEqual(bm25(['a'], []), [])
        self.assertEqual(bm25(['a'], [[], []]), [0.0, 0.0])
    def test_repeated_query_terms_do_not_double_count(self):
        self.assertEqual(bm25(['a'], [['a']]), bm25(['a', 'a'], [['a']]))
    def test_ties_are_explicit_and_deterministic(self):
        self.assertEqual(ranking([1, 1, 0], ['b', 'a', 'c']), ['a', 'b', 'c'])
    def test_invalid_scores_rejected(self):
        for scores, ids in [([1], ['a', 'b']), ([1, 2], ['a', 'a']), ([float('nan')], ['a'])]:
            with self.assertRaises(ValueError): ranking(scores, ids)
    def test_hit_counts(self):
        self.assertEqual(hits_at([['a', 'b'], ['a', 'b']], ['a', 'b'], 1), 1)
        self.assertEqual(hits_at([['a', 'b'], ['a', 'b']], ['a', 'b'], 2), 2)
    def test_invalid_metrics_rejected(self):
        for ranks, gold, k in [([], [], 1), ([['a']], ['a'], 0), ([['a']], [], 1)]:
            with self.assertRaises(ValueError): hits_at(ranks, gold, k)
    def test_fixture_has_unambiguous_document_keys(self):
        x = json.loads(Path(__file__).with_name('fixture.json').read_text())
        ids = [d['id'] for d in x['documents']]
        self.assertEqual(len(ids), len(set(ids)))
        self.assertTrue(all(q['gold'] in ids for q in x['queries']))

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