# tests/test_cyberleninka.py
import unittest
from curl_cffi import requests
from paper_search_mcp.academic_platforms.cyberleninka import CyberLeninkaSearcher


def check_api_accessible():
    """Check if CyberLeninka is accessible"""
    try:
        response = requests.get(
            "https://cyberleninka.ru",
            impersonate="chrome",
            timeout=30
        )
        return response.status_code == 200
    except:
        return False


class TestCyberLeninkaSearcher(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.api_accessible = check_api_accessible()
        if not cls.api_accessible:
            print("\nWarning: CyberLeninka is not accessible, some tests will be skipped")

    def setUp(self):
        self.searcher = CyberLeninkaSearcher()

    def test_search(self):
        if not self.api_accessible:
            self.skipTest("CyberLeninka is not accessible")

        papers = self.searcher.search("искусственный интеллект", max_results=5)
        print(f"Found {len(papers)} papers for query 'искусственный интеллект':")
        for i, paper in enumerate(papers, 1):
            print(f"{i}. {paper.title[:70]}...")
            print(f"   Authors: {', '.join(paper.authors[:2]) if paper.authors else 'N/A'}")
            print(f"   Source: {paper.source}")
            print(f"   Year: {paper.extra.get('year', 'N/A')}")
            print()
        self.assertIsInstance(papers, list)
        if papers:
            self.assertTrue(papers[0].title)
            self.assertEqual(papers[0].source, "cyberleninka")

    def test_search_with_date_filter(self):
        if not self.api_accessible:
            self.skipTest("CyberLeninka is not accessible")

        papers = self.searcher.search(
            "экономика",
            max_results=3,
            date_from="2023-01-01",
            date_to="2024-12-31"
        )
        print(f"Found {len(papers)} papers with date filter (2023-2024)")
        self.assertIsInstance(papers, list)

    def test_search_with_catalog_filter(self):
        if not self.api_accessible:
            self.skipTest("CyberLeninka is not accessible")

        # Search VAK indexed journals only
        papers = self.searcher.search(
            "финансы",
            max_results=3,
            catalog="vak"
        )
        print(f"Found {len(papers)} VAK papers for 'финансы'")
        self.assertIsInstance(papers, list)

    def test_search_with_category_filter(self):
        if not self.api_accessible:
            self.skipTest("CyberLeninka is not accessible")

        # Search economics category
        papers = self.searcher.search(
            "инвестиции",
            max_results=3,
            category="economics"
        )
        print(f"Found {len(papers)} economics papers for 'инвестиции'")
        self.assertIsInstance(papers, list)

    def test_get_paper_by_id(self):
        if not self.api_accessible:
            self.skipTest("CyberLeninka is not accessible")

        # First search to get a valid paper ID
        papers = self.searcher.search("машинное обучение", max_results=1)
        if papers:
            paper_id = papers[0].paper_id
            paper = self.searcher.get_paper_by_id(paper_id)
            if paper:
                print(f"Retrieved paper by ID: {paper.title[:60]}...")
                self.assertEqual(paper.paper_id, paper_id)
                self.assertTrue(paper.title)
                self.assertEqual(paper.source, "cyberleninka")

    def test_impersonate_setting(self):
        """Test that curl_cffi impersonate is configured"""
        self.assertEqual(self.searcher.impersonate, "chrome")

    def test_catalog_constants(self):
        """Test that catalog constants are defined"""
        self.assertEqual(self.searcher.CATALOGS["vak"], 8)
        self.assertEqual(self.searcher.CATALOGS["rsci"], 22)
        self.assertEqual(self.searcher.CATALOGS["scopus"], 2)

    def test_category_constants(self):
        """Test that category constants are defined"""
        self.assertEqual(self.searcher.CATEGORIES["economics"], 35)
        self.assertIn("law", self.searcher.CATEGORIES)
        self.assertIn("medicine", self.searcher.CATEGORIES)


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