from unittest.mock import patch, MagicMock
from juris_base.tiers.tier2_session import BaseSessionClient
from juris_base.models import JurisDocument, SearchResult


class ConcreteSessionClient(BaseSessionClient):
    INIT_URL = "https://example.gov.ar/consulta.html"

    def search(self, query: str, **filters) -> dict:
        opener, _ = self._make_opener()
        self._init_session(opener)
        data = self._post_form(opener, "https://example.gov.ar/buscar.html",
                               {"q": query}, xhr=True)
        return {"total": data.get("total", 0), "results": []}

    def get(self, id: str) -> JurisDocument:
        opener, _ = self._make_opener()
        self._init_session(opener)
        data = self._get_json(opener, f"https://example.gov.ar/doc/{id}")
        return JurisDocument(id=id, texto_completo=data.get("body", ""))


def _mock_response(body: bytes, headers=None):
    resp = MagicMock()
    resp.read.return_value = body
    resp.headers = MagicMock()
    resp.headers.get.return_value = ""
    resp.__enter__ = lambda s: s
    resp.__exit__ = MagicMock(return_value=False)
    return resp


def test_make_opener_returns_opener_and_jar():
    client = ConcreteSessionClient()
    opener, jar = client._make_opener()
    assert opener is not None
    assert jar is not None


def test_init_session_makes_get_request():
    client = ConcreteSessionClient()
    opener, _ = client._make_opener()
    with patch.object(opener, "open", return_value=_mock_response(b"<html/>")):
        client._init_session(opener)  # should not raise
