"""API response wrapper for the Cerebe SDK."""

from __future__ import annotations

from typing import Any, Generic, TypeVar

from pydantic import BaseModel

T = TypeVar("T")


class ResponseMeta(BaseModel):
    """Metadata from API response."""

    request_id: str | None = None
    org_id: str | None = None
    project_id: str | None = None
    version: str | None = None
    usage: dict[str, Any] | None = None


class APIResponse(Generic[T]):
    """Wrapper around API responses providing access to data and metadata."""

    def __init__(self, data: T, meta: ResponseMeta | None = None, raw: dict[str, Any] | None = None) -> None:
        self.data = data
        self.meta = meta or ResponseMeta()
        self.raw = raw or {}

    @property
    def request_id(self) -> str | None:
        return self.meta.request_id

    def __repr__(self) -> str:
        return f"APIResponse(data={self.data!r}, request_id={self.request_id!r})"

    @classmethod
    def from_response(cls, body: dict[str, Any], data_type: type[T] | None = None) -> APIResponse[T]:
        """Parse a standard envelope response."""
        raw_data = body.get("data", body)
        raw_meta = body.get("meta", {})

        meta = ResponseMeta(**raw_meta) if raw_meta else ResponseMeta()

        if data_type and isinstance(raw_data, dict) and issubclass(data_type, BaseModel):
            data = data_type.model_validate(raw_data)
        else:
            data = raw_data

        return cls(data=data, meta=meta, raw=body)
