from unittest.mock import patch, MagicMock
from juris_base.tiers.tier1_rest import BaseRestClient
from juris_base.models import SearchResult, JurisDocument


class ConcreteRestClient(BaseRestClient):
    BASE_URL = "https://example.gov.ar"

    def search(self, query: str, **filters) -> dict:
        data = self._get_json(f"{self.BASE_URL}/search?q={query}")
        return {"total": data["total"], "results": [
            SearchResult(id=str(r["id"]), texto=r["text"], raw=r)
            for r in data["items"]
        ]}

    def get(self, id: str) -> JurisDocument:
        data = self._get_json(f"{self.BASE_URL}/doc/{id}")
        return JurisDocument(id=id, texto_completo=data["body"])


def test_get_json_parses_response():
    client = ConcreteRestClient()
    mock_response = MagicMock()
    mock_response.read.return_value = b'{"total": 2, "items": []}'
    mock_response.__enter__ = lambda s: s
    mock_response.__exit__ = MagicMock(return_value=False)

    with patch("urllib.request.urlopen", return_value=mock_response):
        result = client._get_json("https://example.gov.ar/search?q=test")
    assert result["total"] == 2


def test_get_json_raises_on_http_error():
    import urllib.error
    from juris_base.exceptions import JurisError
    client = ConcreteRestClient()
    with patch("urllib.request.urlopen", side_effect=urllib.error.HTTPError(
        None, 404, "Not Found", {}, None
    )):
        try:
            client._get_json("https://example.gov.ar/missing")
            assert False, "should have raised"
        except JurisError:
            pass
