# tests/test_ssrn.py
import unittest
from curl_cffi import requests
from paper_search_mcp.academic_platforms.ssrn import SSRNSearcher


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


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

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

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

        papers = self.searcher.search("corporate governance", max_results=5)
        print(f"Found {len(papers)} papers for query 'corporate governance':")
        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"   DOI: {paper.doi or 'N/A'}")
            print()
        # SSRN may return 0 results due to scraping limitations
        self.assertIsInstance(papers, list)
        if papers:
            self.assertTrue(papers[0].title)
            self.assertEqual(papers[0].source, "ssrn")

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

        papers = self.searcher.search(
            "blockchain",
            max_results=3,
            date_from="2022-01-01",
            date_to="2023-12-31"
        )
        print(f"Found {len(papers)} papers with date filter (2022-2023)")
        self.assertIsInstance(papers, list)

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

        # Known SSRN paper ID
        paper_id = "3550274"  # A commonly cited paper
        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, "ssrn")
        else:
            print(f"Paper with ID {paper_id} not found or page structure changed")

    def test_search_by_doi(self):
        if not self.api_accessible:
            self.skipTest("SSRN is not accessible")

        # SSRN DOI format
        doi = "10.2139/ssrn.3550274"
        paper = self.searcher.search_by_doi(doi)

        if paper:
            print(f"Retrieved paper by DOI: {paper.title[:60]}...")
            self.assertTrue(paper.title)
        else:
            print(f"Paper with DOI {doi} not found")

    def test_search_empty_query(self):
        if not self.api_accessible:
            self.skipTest("SSRN is not accessible")

        papers = self.searcher.search("", max_results=5)
        self.assertIsInstance(papers, list)

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

    def test_rate_limiting(self):
        """Test that rate limiting is applied"""
        import time

        if not self.api_accessible:
            self.skipTest("SSRN is not accessible")

        start = time.time()
        # Make two quick requests
        self.searcher._rate_limit(0.5)
        self.searcher._rate_limit(0.5)
        elapsed = time.time() - start

        # Should have waited at least 0.5 seconds
        self.assertGreaterEqual(elapsed, 0.4)

    def test_paper_fields(self):
        if not self.api_accessible:
            self.skipTest("SSRN is not accessible")

        papers = self.searcher.search("economics", max_results=1)
        if papers:
            paper = papers[0]
            # Check required fields exist
            self.assertIsNotNone(paper.paper_id)
            self.assertIsNotNone(paper.title)
            self.assertIsInstance(paper.authors, list)
            self.assertIsInstance(paper.abstract, str)
            self.assertEqual(paper.source, "ssrn")
            # SSRN papers should have DOI in format 10.2139/ssrn.XXXXX
            if paper.doi:
                self.assertIn("ssrn", paper.doi.lower())


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