import json
from contextlib import asynccontextmanager

import httpx
import respx
from fastmcp import Client, FastMCP

from mcsci_hub.cache import TTLCache
from mcsci_hub.clients.crossref import CrossRefClient
from mcsci_hub.clients.openalex import OpenAlexClient
from mcsci_hub.clients.scihub import SciHubClient
from mcsci_hub.clients.semantic_scholar import SemanticScholarClient
from mcsci_hub.tools import register_all
from tests.conftest import SAMPLE_S2_CITATIONS, SAMPLE_S2_REFERENCES

S2_BASE = "https://api.semanticscholar.org/graph/v1"


def _make_server() -> FastMCP:
    @asynccontextmanager
    async def test_lifespan(server: FastMCP):
        async with httpx.AsyncClient() as http_client:
            yield {
                "crossref": CrossRefClient(http_client, mailto="test@test.com"),
                "openalex": OpenAlexClient(http_client, mailto="test@test.com"),
                "s2": SemanticScholarClient(http_client),
                "scihub": SciHubClient(http_client, mirrors=["sci-hub.test"]),
                "cache": TTLCache(max_size=100, ttl=60),
            }

    app = FastMCP("test-mcsci-hub", lifespan=test_lifespan)
    register_all(app)
    return app


@respx.mock
async def test_get_citations():
    respx.get(f"{S2_BASE}/paper/DOI:10.1038/nature12373/citations").mock(
        return_value=httpx.Response(200, json=SAMPLE_S2_CITATIONS)
    )

    async with Client(_make_server()) as client:
        result = await client.call_tool("get_citations", {"doi": "10.1038/nature12373"})
        data = json.loads(result.content[0].text)
        assert data["count"] == 1
        assert "BERT" in data["citations"][0]["title"]
        assert data["citations"][0]["is_influential"] is True


@respx.mock
async def test_get_references():
    respx.get(f"{S2_BASE}/paper/DOI:10.1038/nature12373/references").mock(
        return_value=httpx.Response(200, json=SAMPLE_S2_REFERENCES)
    )

    async with Client(_make_server()) as client:
        result = await client.call_tool("get_references", {"doi": "10.1038/nature12373"})
        data = json.loads(result.content[0].text)
        assert data["count"] == 1
        assert "Neural Machine Translation" in data["references"][0]["title"]


@respx.mock
async def test_get_citations_empty():
    respx.get(f"{S2_BASE}/paper/DOI:10.0000/new/citations").mock(
        return_value=httpx.Response(200, json={"data": []})
    )

    async with Client(_make_server()) as client:
        result = await client.call_tool("get_citations", {"doi": "10.0000/new"})
        data = json.loads(result.content[0].text)
        assert data["citations"] == []
