"""Shared HTTP helpers for resource classes."""

from __future__ import annotations

import requests

from .exceptions import APIError, NotFoundError, ValidationError
from .types import HTTPValidationError


class BaseResource:
    """Base class providing HTTP session and error handling."""

    def __init__(self, session: requests.Session, base_url: str) -> None:
        self._session = session
        self._base_url = base_url

    def _url(self, path: str) -> str:
        return f"{self._base_url}{path}"

    def _raise_for_status(self, resp: requests.Response) -> None:
        if resp.status_code < 400:
            return

        if resp.status_code == 404:
            detail = resp.json().get("detail", "Not found") if resp.text else "Not found"
            raise NotFoundError(detail)

        if resp.status_code == 422:
            body = HTTPValidationError.model_validate(resp.json())
            raise ValidationError(body)

        detail = resp.text
        try:
            detail = resp.json().get("detail", detail)
        except Exception:
            pass
        raise APIError(resp.status_code, detail)
