"""Minimal dependency-free LotContext API v1 client."""

from __future__ import annotations

import json
from typing import Any
from urllib.error import HTTPError
from urllib.parse import urlencode
from urllib.request import Request, urlopen


class LotContextError(RuntimeError):
    """An unsuccessful LotContext API response."""


class LotContextClient:
    def __init__(
        self,
        api_key: str,
        base_url: str = "https://lotcontext.com/api/v1",
        timeout: float = 15,
    ) -> None:
        self.api_key = api_key
        self.base_url = base_url.rstrip("/")
        self.timeout = timeout

    def search_properties(self, **params: str | int | bool) -> dict[str, Any]:
        return self._get("/properties", params)

    def get_property(self, property_id: str) -> dict[str, Any]:
        return self._get(f"/properties/{property_id}")

    def list_changes(self, **params: str | int) -> dict[str, Any]:
        return self._get("/changes", params)

    def _get(self, path: str, params: dict[str, Any] | None = None) -> dict[str, Any]:
        query = f"?{urlencode(params)}" if params else ""
        request = Request(
            f"{self.base_url}{path}{query}",
            headers={"Authorization": f"Bearer {self.api_key}", "Accept": "application/json"},
        )
        try:
            with urlopen(request, timeout=self.timeout) as response:  # noqa: S310
                return json.load(response)
        except HTTPError as error:
            body = error.read().decode("utf-8", errors="replace")
            raise LotContextError(f"LotContext API {error.code}: {body}") from error
