import unittest

from indexer.links import extract_labeled_links, extract_links, extract_post_id


class LinkTests(unittest.TestCase):
    def test_extracts_variants(self):
        text = """
        [Next](https://www.reddit.com/r/HFY/comments/aaa222/the_last_terran_part_2/)
        [Prev](https://redd.it/aaa111)
        See also /r/HFY/comments/abcd123/something/ and <a href="/comments/ffff001/x">first</a>
        """
        links = extract_links(text)
        self.assertEqual(extract_post_id("https://old.reddit.com/r/HFY/comments/aaa222/slug/"), "aaa222")
        self.assertIn("aaa222", links.next_ids)
        self.assertIn("aaa111", links.prev_ids)
        self.assertIn("ffff001", links.first_ids)
        self.assertIn("abcd123", links.all_ids)

    def test_empty(self):
        links = extract_links("")
        self.assertEqual(links.all_ids, ())

    def test_labeled_links_keep_document_order(self):
        text = """
        [Prev](https://redd.it/aaa111)
        See [this chapter](https://www.reddit.com/r/HFY/comments/abcd123/something/)
        [Next](https://www.reddit.com/r/HFY/comments/aaa222/the_last_terran_part_2/)
        """
        labeled = extract_labeled_links(text)
        self.assertEqual([ln.id for ln in labeled], ["aaa111", "abcd123", "aaa222"])
        self.assertEqual([ln.kind for ln in labeled], ["prev", "other", "next"])
        self.assertEqual(extract_links(text).links, tuple(labeled))


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