# tests/test_core.py
import unittest
import os
import requests
from paper_search_mcp.academic_platforms.core import CoreSearcher


def check_api_accessible():
    """Check if CORE API is accessible"""
    try:
        response = requests.get(
            "https://api.core.ac.uk/v3/search/works",
            params={"q": "test", "limit": 1},
            headers={"Accept": "application/json"},
            timeout=10
        )
        return response.status_code == 200
    except:
        return False


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

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

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

        papers = self.searcher.search("machine learning", max_results=5)
        print(f"Found {len(papers)} papers for query 'machine learning':")
        for i, paper in enumerate(papers, 1):
            print(f"{i}. {paper.title[:70]}...")
            print(f"   Authors: {', '.join(paper.authors[:2])}{'...' if len(paper.authors) > 2 else ''}")
            print(f"   Source: {paper.source}")
            print(f"   DOI: {paper.doi or 'N/A'}")
            if paper.extra:
                print(f"   Repository: {paper.extra.get('source_repository', 'N/A')}")
            print()
        self.assertTrue(len(papers) > 0)
        if papers:
            self.assertTrue(papers[0].title)
            self.assertEqual(papers[0].source, "core")

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

        papers = self.searcher.search(
            "neural networks",
            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.assertTrue(len(papers) >= 0)

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

        # First search to get a valid paper ID
        papers = self.searcher.search("computer science", 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)
            else:
                print(f"Paper with ID {paper_id} not found")

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

        # Test with a known DOI
        known_doi = "10.1038/nature12373"
        paper = self.searcher.search_by_doi(known_doi)

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

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

        papers = self.searcher.search("", max_results=5)
        # Empty query may return results or empty list depending on API
        self.assertIsInstance(papers, list)

    def test_search_max_results_limit(self):
        if not self.api_accessible:
            self.skipTest("CORE API is not accessible")

        # CORE API max is 100
        papers = self.searcher.search("data science", max_results=150)
        self.assertTrue(len(papers) <= 100)

    def test_user_agent_header(self):
        self.assertIn("paper-search-mcp", self.searcher.session.headers.get('User-Agent', ''))

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

        papers = self.searcher.search("biology", 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, "core")


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