import pytest

httpx = pytest.importorskip("httpx")
respx = pytest.importorskip("respx")

from citesleuth.cache import NullCache
from citesleuth.providers.dblp import DBLPProvider
from citesleuth.providers.openlibrary import OpenLibraryProvider
from citesleuth.providers.semanticscholar import SemanticScholarProvider


@respx.mock
def test_semanticscholar_lookup_by_id():
    url = "https://api.semanticscholar.org/graph/v1/paper/DOI:10.1109/CVPR.2016.90"
    payload = {
        "paperId": "123",
        "title": "Deep Residual Learning for Image Recognition",
        "year": 2016,
        "authors": [{"name": "Kaiming He"}],
        "venue": "CVPR",
        "externalIds": {"DOI": "10.1109/CVPR.2016.90"},
        "url": "https://www.semanticscholar.org/paper/123",
    }
    respx.get(url).mock(return_value=httpx.Response(200, json=payload))

    provider = SemanticScholarProvider(NullCache())
    results = provider.lookup_by_id("10.1109/CVPR.2016.90", "doi")
    assert results
    assert results[0].ids.get("doi") == "10.1109/CVPR.2016.90"


@respx.mock
def test_dblp_search():
    url = "https://dblp.org/search/publ/api"
    payload = {
        "result": {
            "hits": {
                "hit": [
                    {
                        "info": {
                            "title": "Deep Residual Learning for Image Recognition",
                            "year": "2016",
                            "venue": "CVPR",
                            "key": "conf/cvpr/HeZR016",
                            "url": "https://dblp.org/rec/conf/cvpr/HeZR016",
                            "authors": {"author": [{"text": "Kaiming He"}]},
                        }
                    }
                ]
            }
        }
    }
    respx.get(url).mock(return_value=httpx.Response(200, json=payload))

    provider = DBLPProvider(NullCache())
    results = provider.search("Deep Residual Learning")
    assert results
    assert results[0].title == "Deep Residual Learning for Image Recognition"


@respx.mock
def test_openlibrary_isbn():
    url = "https://openlibrary.org/isbn/9780262035613.json"
    payload = {
        "title": "Deep Learning",
        "publish_date": "2016",
        "publishers": ["MIT Press"],
        "isbn_13": ["9780262035613"],
        "key": "/books/OL123M",
    }
    respx.get(url).mock(return_value=httpx.Response(200, json=payload))

    provider = OpenLibraryProvider(NullCache())
    results = provider.lookup_by_id("9780262035613", "isbn")
    assert results
    assert results[0].ids.get("isbn") == "9780262035613"
