from __future__ import annotations

from typing import TYPE_CHECKING, Any, List, Optional

from cardog.types.safety import SafetyDetail, SafetyStats

if TYPE_CHECKING:
    from cardog._base_client import AsyncAPIClient, SyncAPIClient


class SyncSafetyResource:
    """NHTSA vehicle safety ratings."""

    def __init__(self, client: SyncAPIClient) -> None:
        self._client = client

    def search(
        self,
        *,
        makes: Optional[List[str]] = None,
        models: Optional[List[str]] = None,
        year_min: Optional[int] = None,
        year_max: Optional[int] = None,
        overall_stars: Optional[List[str]] = None,
        limit: Optional[int] = None,
        offset: Optional[int] = None,
        sort: Optional[str] = None,
        order: Optional[str] = None,
    ) -> Any:
        """Search safety ratings."""
        params: dict[str, Any] = {}
        if makes:
            params["makes"] = ",".join(makes)
        if models:
            params["models"] = ",".join(models)
        if year_min is not None:
            params["yearMin"] = year_min
        if year_max is not None:
            params["yearMax"] = year_max
        if overall_stars:
            params["overallStars"] = ",".join(overall_stars)
        if limit is not None:
            params["limit"] = limit
        if offset is not None:
            params["offset"] = offset
        if sort:
            params["sort"] = sort
        if order:
            params["order"] = order
        return self._client._get("/safety/search", params=params)

    def get(self, safety_id: int) -> SafetyDetail:
        """Get a safety review by ID."""
        return self._client._get(f"/safety/{safety_id}", model=SafetyDetail)

    def get_by_vehicle(self, make: str, model: str, year: int) -> List[SafetyDetail]:
        """Get safety reviews for a specific vehicle."""
        return self._client._get(f"/safety/vehicle/{make}/{model}/{year}")

    def stats_overview(self) -> SafetyStats:
        """Get aggregate safety statistics."""
        data = self._client._get("/safety/stats/overview")
        inner = data.get("data", data) if isinstance(data, dict) else data
        return SafetyStats.model_validate(inner)


class AsyncSafetyResource:
    """NHTSA vehicle safety ratings (async)."""

    def __init__(self, client: AsyncAPIClient) -> None:
        self._client = client

    async def search(
        self,
        *,
        makes: Optional[List[str]] = None,
        models: Optional[List[str]] = None,
        year_min: Optional[int] = None,
        year_max: Optional[int] = None,
        overall_stars: Optional[List[str]] = None,
        limit: Optional[int] = None,
        offset: Optional[int] = None,
        sort: Optional[str] = None,
        order: Optional[str] = None,
    ) -> Any:
        """Search safety ratings."""
        params: dict[str, Any] = {}
        if makes:
            params["makes"] = ",".join(makes)
        if models:
            params["models"] = ",".join(models)
        if year_min is not None:
            params["yearMin"] = year_min
        if year_max is not None:
            params["yearMax"] = year_max
        if overall_stars:
            params["overallStars"] = ",".join(overall_stars)
        if limit is not None:
            params["limit"] = limit
        if offset is not None:
            params["offset"] = offset
        if sort:
            params["sort"] = sort
        if order:
            params["order"] = order
        return await self._client._get("/safety/search", params=params)

    async def get(self, safety_id: int) -> SafetyDetail:
        """Get a safety review by ID."""
        return await self._client._get(f"/safety/{safety_id}", model=SafetyDetail)

    async def get_by_vehicle(
        self, make: str, model: str, year: int
    ) -> List[SafetyDetail]:
        """Get safety reviews for a specific vehicle."""
        return await self._client._get(f"/safety/vehicle/{make}/{model}/{year}")

    async def stats_overview(self) -> SafetyStats:
        """Get aggregate safety statistics."""
        data = await self._client._get("/safety/stats/overview")
        inner = data.get("data", data) if isinstance(data, dict) else data
        return SafetyStats.model_validate(inner)
