import json

import httpx
import respx
from fastmcp import Client

from tests.conftest import (
    SAMPLE_CROSSREF_SEARCH,
    SAMPLE_OPENALEX_SEARCH,
    make_test_server,
)


@respx.mock
async def test_search_papers_openalex():
    respx.get("https://api.openalex.org/works").mock(
        return_value=httpx.Response(200, json=SAMPLE_OPENALEX_SEARCH)
    )

    async with Client(make_test_server()) as client:
        result = await client.call_tool("search_papers", {"query": "attention"})
        data = json.loads(result.content[0].text)
        assert data["count"] == 1
        assert data["results"][0]["doi"] == "10.1038/nature12373"
        assert data["results"][0]["source"] == "openalex"


@respx.mock
async def test_search_papers_crossref_fallback():
    respx.get("https://api.openalex.org/works").mock(
        return_value=httpx.Response(200, json={"results": []})
    )
    respx.get("https://api.crossref.org/works").mock(
        return_value=httpx.Response(200, json=SAMPLE_CROSSREF_SEARCH)
    )

    async with Client(make_test_server()) as client:
        result = await client.call_tool("search_papers", {"query": "attention"})
        data = json.loads(result.content[0].text)
        assert data["count"] == 1
        assert data["results"][0]["source"] == "crossref"


@respx.mock
async def test_search_papers_no_results():
    respx.get("https://api.openalex.org/works").mock(
        return_value=httpx.Response(200, json={"results": []})
    )
    respx.get("https://api.crossref.org/works").mock(
        return_value=httpx.Response(200, json={"message": {"items": []}})
    )

    async with Client(make_test_server()) as client:
        result = await client.call_tool("search_papers", {"query": "zzzznothing"})
        data = json.loads(result.content[0].text)
        assert data["results"] == []
