"""Tests for huntpdf.resolvers.pubmed."""

from pathlib import Path
from unittest.mock import MagicMock

import pytest
import respx
from httpx import Response

from huntpdf.errors import PDFNotFound
from huntpdf.resolvers.pubmed import resolve_pubmed

_IDCONV_URL = "https://www.ncbi.nlm.nih.gov/pmc/utils/idconv/v1.0/"


class TestResolvePubmed:
    @respx.mock
    def test_pmid_with_pmcid(self, monkeypatch, tmp_path):
        respx.get(_IDCONV_URL).mock(
            return_value=Response(
                200,
                json={"records": [{"pmcid": "PMC7654321", "doi": "10.1234/test"}]},
            )
        )
        expected = tmp_path / "PMC7654321.pdf"
        mock_pmc = MagicMock(return_value=expected)
        monkeypatch.setattr("huntpdf.resolvers.pubmed.resolve_pmc", mock_pmc)

        result = resolve_pubmed("12345678", expected)
        assert result == expected
        mock_pmc.assert_called_once_with("PMC7654321", expected)

    @respx.mock
    def test_pmid_with_doi_only(self, monkeypatch, tmp_path):
        respx.get(_IDCONV_URL).mock(
            return_value=Response(
                200,
                json={"records": [{"doi": "10.1234/test"}]},
            )
        )
        expected = tmp_path / "paper.pdf"
        mock_doi = MagicMock(return_value=expected)
        monkeypatch.setattr("huntpdf.resolvers.pubmed.resolve_doi", mock_doi)

        result = resolve_pubmed("12345678", expected)
        assert result == expected
        mock_doi.assert_called_once_with("10.1234/test", expected)

    @respx.mock
    def test_pmid_with_neither(self):
        respx.get(_IDCONV_URL).mock(
            return_value=Response(
                200,
                json={"records": [{"pmid": "12345678"}]},
            )
        )
        with pytest.raises(PDFNotFound, match="No PMCID or DOI"):
            resolve_pubmed("12345678")

    @respx.mock
    def test_no_records(self):
        respx.get(_IDCONV_URL).mock(
            return_value=Response(200, json={"records": []})
        )
        with pytest.raises(PDFNotFound, match="No records found"):
            resolve_pubmed("99999999")

    @respx.mock
    def test_pmcid_preferred_over_doi(self, monkeypatch, tmp_path):
        """When both PMCID and DOI exist, PMCID takes priority."""
        respx.get(_IDCONV_URL).mock(
            return_value=Response(
                200,
                json={"records": [{"pmcid": "PMC111", "doi": "10.1234/test"}]},
            )
        )
        expected = tmp_path / "paper.pdf"
        mock_pmc = MagicMock(return_value=expected)
        mock_doi = MagicMock()
        monkeypatch.setattr("huntpdf.resolvers.pubmed.resolve_pmc", mock_pmc)
        monkeypatch.setattr("huntpdf.resolvers.pubmed.resolve_doi", mock_doi)

        resolve_pubmed("12345678", expected)
        mock_pmc.assert_called_once()
        mock_doi.assert_not_called()
