from __future__ import annotations

import json
import urllib.error
import urllib.request
from abc import ABC, abstractmethod

from juris_base.exceptions import JurisError
from juris_base.models import JurisDocument, SearchResult

DEFAULT_UA = (
    "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 "
    "(KHTML, like Gecko) Chrome/144.0.0.0 Safari/537.36"
)


class BaseRestClient(ABC):
    """Tier 1: JSON REST API with no auth or CAPTCHA."""

    user_agent: str = DEFAULT_UA
    timeout: int = 30

    def _get_json(self, url: str, headers: dict | None = None) -> dict:
        req = urllib.request.Request(url, headers={
            "Accept": "application/json",
            "User-Agent": self.user_agent,
            **(headers or {}),
        })
        try:
            with urllib.request.urlopen(req, timeout=self.timeout) as resp:
                return json.loads(resp.read().decode("utf-8"))
        except urllib.error.HTTPError as e:
            raise JurisError(f"HTTP {e.code} from {url}") from e
        except urllib.error.URLError as e:
            raise JurisError(f"Connection error: {e.reason}") from e

    @abstractmethod
    def search(self, query: str, **filters) -> dict:
        ...

    @abstractmethod
    def get(self, id: str) -> JurisDocument:
        ...

    def download(self, id: str) -> bytes:
        raise NotImplementedError
