#!/usr/bin/env python3
"""
Unit tests for literature_search.py's candidate merging and BibTeX generation.

Run: python -m unittest discover -s .claude/skills/literature-search-verify/scripts
"""
import os
import sys
import unittest

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import literature_search as ls


class TestMergeCandidates(unittest.TestCase):
    def test_dedupes_same_paper_across_sources_and_fills_missing_fields(self):
        items = [
            {"source": "arxiv", "title": "Deep Learning for Aeromagnetic Compensation",
             "arxiv_id": "2401.00001", "doi": None, "year": "2024"},
            {"source": "crossref", "title": "Deep Learning for Aeromagnetic Compensation",
             "arxiv_id": None, "doi": "10.1/x", "year": 2024, "venue": "Some Journal"},
        ]
        merged = ls.merge_candidates(items)
        self.assertEqual(len(merged), 1)
        self.assertEqual(merged[0]["arxiv_id"], "2401.00001")
        self.assertEqual(merged[0]["doi"], "10.1/x")
        self.assertEqual(sorted(merged[0]["sources"]), ["arxiv", "crossref"])

    def test_distinct_titles_are_not_merged(self):
        items = [
            {"source": "arxiv", "title": "Paper About Cats"},
            {"source": "crossref", "title": "Paper About Dogs"},
        ]
        self.assertEqual(len(ls.merge_candidates(items)), 2)


class TestBibtexKey(unittest.TestCase):
    def test_collision_gets_letter_suffix(self):
        used = set()
        key1 = ls.make_bibtex_key({"authors": ["Jane Smith"], "year": "2020"}, used)
        key2 = ls.make_bibtex_key({"authors": ["John Smith"], "year": "2020"}, used)
        self.assertEqual(key1, "smith2020")
        self.assertEqual(key2, "smith2020a")

    def test_no_authors_falls_back_to_unknown(self):
        key = ls.make_bibtex_key({"authors": [], "year": "2020"}, set())
        self.assertEqual(key, "unknown2020")


class TestToBibtex(unittest.TestCase):
    def test_arxiv_only_candidate_uses_misc_with_eprint(self):
        cand = {"authors": ["A B"], "title": "T", "year": "2024",
                "arxiv_id": "2401.00001", "venue": None, "doi": None}
        bib = ls.to_bibtex(cand, "b2024")
        self.assertTrue(bib.startswith("@misc{b2024,"))
        self.assertIn("eprint = {2401.00001}", bib)

    def test_candidate_with_venue_uses_article_with_doi(self):
        cand = {"authors": ["A B"], "title": "T", "year": "2024",
                "arxiv_id": None, "venue": "Some Journal", "doi": "10.1/x"}
        bib = ls.to_bibtex(cand, "b2024")
        self.assertTrue(bib.startswith("@article{b2024,"))
        self.assertIn("doi = {10.1/x}", bib)


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