from __future__ import annotations

import httpx

from .models import (
    OGImageAsyncResponse,
    OGImageGenerateRequest,
    OGImageManagedResponse,
    OGImagePreset,
    OGImagePresetRequest,
    OGImagePublicUrl,
    OGImageResponse,
    OGImageStatus,
    PaginatedOGImageManagedResponseList,
    PaginatedOGImagePresetList,
    PaginatedOGImageResponseList,
    PatchedOGImagePresetRequest,
)


class OgimageOgimageAPI:
    """API endpoints for Ogimage."""

    def __init__(self, client: httpx.AsyncClient):
        """Initialize sub-client with shared httpx client."""
        self._client = client

    async def list(
        self,
        ordering: str | None = None,
        page: int | None = None,
        page_size: int | None = None,
        search: str | None = None,
    ) -> list[PaginatedOGImageResponseList]:
        """
        Mixin for ViewSets that need to filter by API key ownership. Provides
        consistent queryset filtering across apps: - Superusers see all records
        - Test API key in dev mode: see all records (like superuser) - API key
        auth: filter by api_key - User auth: filter by api_key__user Usage:
        class MyViewSet(SDKAPIKeyFilterMixin, viewsets.ModelViewSet): queryset =
        MyModel.objects.all() api_key_field = "api_key" # FK field name
        (default) The model must have a FK to SDKAPIKey named `api_key` (or
        override api_key_field).
        """
        url = "/api/ogimage/"
        _params = {
            k: v for k, v in {
                "ordering": ordering,
                "page": page,
                "page_size": page_size,
                "search": search,
            }.items() if v is not None
        }
        response = await self._client.get(url, params=_params)
        if not response.is_success:
            try:
                error_body = response.json()
            except Exception:
                error_body = response.text
            msg = f"{response.status_code}: {error_body}"
            raise httpx.HTTPStatusError(
                msg, request=response.request, response=response
            )
        return PaginatedOGImageResponseList.model_validate(response.json())


    async def retrieve(self, id: str) -> OGImageResponse:
        """
        Mixin for ViewSets that need to filter by API key ownership. Provides
        consistent queryset filtering across apps: - Superusers see all records
        - Test API key in dev mode: see all records (like superuser) - API key
        auth: filter by api_key - User auth: filter by api_key__user Usage:
        class MyViewSet(SDKAPIKeyFilterMixin, viewsets.ModelViewSet): queryset =
        MyModel.objects.all() api_key_field = "api_key" # FK field name
        (default) The model must have a FK to SDKAPIKey named `api_key` (or
        override api_key_field).
        """
        url = f"/api/ogimage/{id}/"
        response = await self._client.get(url)
        if not response.is_success:
            try:
                error_body = response.json()
            except Exception:
                error_body = response.text
            msg = f"{response.status_code}: {error_body}"
            raise httpx.HTTPStatusError(
                msg, request=response.request, response=response
            )
        return OGImageResponse.model_validate(response.json())


    async def public_url_retrieve(self, id: str) -> OGImagePublicUrl:
        """
        Get public OG URL for this image

        Mixin for ViewSets that need to filter by API key ownership. Provides
        consistent queryset filtering across apps: - Superusers see all records
        - Test API key in dev mode: see all records (like superuser) - API key
        auth: filter by api_key - User auth: filter by api_key__user Usage:
        class MyViewSet(SDKAPIKeyFilterMixin, viewsets.ModelViewSet): queryset =
        MyModel.objects.all() api_key_field = "api_key" # FK field name
        (default) The model must have a FK to SDKAPIKey named `api_key` (or
        override api_key_field).
        """
        url = f"/api/ogimage/{id}/public-url/"
        response = await self._client.get(url)
        if not response.is_success:
            try:
                error_body = response.json()
            except Exception:
                error_body = response.text
            msg = f"{response.status_code}: {error_body}"
            raise httpx.HTTPStatusError(
                msg, request=response.request, response=response
            )
        return OGImagePublicUrl.model_validate(response.json())


    async def status_retrieve(self, id: str) -> OGImageStatus:
        """
        Get job status

        Mixin for ViewSets that need to filter by API key ownership. Provides
        consistent queryset filtering across apps: - Superusers see all records
        - Test API key in dev mode: see all records (like superuser) - API key
        auth: filter by api_key - User auth: filter by api_key__user Usage:
        class MyViewSet(SDKAPIKeyFilterMixin, viewsets.ModelViewSet): queryset =
        MyModel.objects.all() api_key_field = "api_key" # FK field name
        (default) The model must have a FK to SDKAPIKey named `api_key` (or
        override api_key_field).
        """
        url = f"/api/ogimage/{id}/status/"
        response = await self._client.get(url)
        if not response.is_success:
            try:
                error_body = response.json()
            except Exception:
                error_body = response.text
            msg = f"{response.status_code}: {error_body}"
            raise httpx.HTTPStatusError(
                msg, request=response.request, response=response
            )
        return OGImageStatus.model_validate(response.json())


    async def generate_create(self, data: OGImageGenerateRequest) -> OGImageResponse:
        """
        Generate OG image (sync)

        Synchronous generation — waits for image, returns CDN URL.
        """
        url = "/api/ogimage/generate/"
        response = await self._client.post(url, json=data.model_dump(mode="json", exclude_unset=True, exclude_none=True))
        if not response.is_success:
            try:
                error_body = response.json()
            except Exception:
                error_body = response.text
            msg = f"{response.status_code}: {error_body}"
            raise httpx.HTTPStatusError(
                msg, request=response.request, response=response
            )
        return OGImageResponse.model_validate(response.json())


    async def generate_async_create(
        self,
        data: OGImageGenerateRequest,
    ) -> OGImageAsyncResponse:
        """
        Generate OG image (async)

        Async generation — queues job, returns immediately with job_id.
        """
        url = "/api/ogimage/generate-async/"
        response = await self._client.post(url, json=data.model_dump(mode="json", exclude_unset=True, exclude_none=True))
        if not response.is_success:
            try:
                error_body = response.json()
            except Exception:
                error_body = response.text
            msg = f"{response.status_code}: {error_body}"
            raise httpx.HTTPStatusError(
                msg, request=response.request, response=response
            )
        return OGImageAsyncResponse.model_validate(response.json())


    async def managed_list(
        self,
        ordering: str | None = None,
        page: int | None = None,
        page_size: int | None = None,
        search: str | None = None,
    ) -> list[PaginatedOGImageManagedResponseList]:
        """
        CRUD for managed LLM OGImages with permanent slug-based stable URLs.
        Managed images are created once via API, generated async in background,
        and served via a stable /og/m/<slug>/ URL the client embeds in HTML
        once.
        """
        url = "/api/ogimage/managed/"
        _params = {
            k: v for k, v in {
                "ordering": ordering,
                "page": page,
                "page_size": page_size,
                "search": search,
            }.items() if v is not None
        }
        response = await self._client.get(url, params=_params)
        if not response.is_success:
            try:
                error_body = response.json()
            except Exception:
                error_body = response.text
            msg = f"{response.status_code}: {error_body}"
            raise httpx.HTTPStatusError(
                msg, request=response.request, response=response
            )
        return PaginatedOGImageManagedResponseList.model_validate(response.json())


    async def managed_update(self, slug: str) -> OGImageManagedResponse:
        """
        CRUD for managed LLM OGImages with permanent slug-based stable URLs.
        Managed images are created once via API, generated async in background,
        and served via a stable /og/m/<slug>/ URL the client embeds in HTML
        once.
        """
        url = f"/api/ogimage/managed/{slug}/"
        response = await self._client.put(url)
        if not response.is_success:
            try:
                error_body = response.json()
            except Exception:
                error_body = response.text
            msg = f"{response.status_code}: {error_body}"
            raise httpx.HTTPStatusError(
                msg, request=response.request, response=response
            )
        return OGImageManagedResponse.model_validate(response.json())


    async def presets_list(
        self,
        ordering: str | None = None,
        page: int | None = None,
        page_size: int | None = None,
        search: str | None = None,
    ) -> list[PaginatedOGImagePresetList]:
        """
        Mixin for ViewSets that need to filter by API key ownership. Provides
        consistent queryset filtering across apps: - Superusers see all records
        - Test API key in dev mode: see all records (like superuser) - API key
        auth: filter by api_key - User auth: filter by api_key__user Usage:
        class MyViewSet(SDKAPIKeyFilterMixin, viewsets.ModelViewSet): queryset =
        MyModel.objects.all() api_key_field = "api_key" # FK field name
        (default) The model must have a FK to SDKAPIKey named `api_key` (or
        override api_key_field).
        """
        url = "/api/ogimage/presets/"
        _params = {
            k: v for k, v in {
                "ordering": ordering,
                "page": page,
                "page_size": page_size,
                "search": search,
            }.items() if v is not None
        }
        response = await self._client.get(url, params=_params)
        if not response.is_success:
            try:
                error_body = response.json()
            except Exception:
                error_body = response.text
            msg = f"{response.status_code}: {error_body}"
            raise httpx.HTTPStatusError(
                msg, request=response.request, response=response
            )
        return PaginatedOGImagePresetList.model_validate(response.json())


    async def presets_create(self, data: OGImagePresetRequest) -> OGImagePreset:
        """
        Mixin for ViewSets that need to filter by API key ownership. Provides
        consistent queryset filtering across apps: - Superusers see all records
        - Test API key in dev mode: see all records (like superuser) - API key
        auth: filter by api_key - User auth: filter by api_key__user Usage:
        class MyViewSet(SDKAPIKeyFilterMixin, viewsets.ModelViewSet): queryset =
        MyModel.objects.all() api_key_field = "api_key" # FK field name
        (default) The model must have a FK to SDKAPIKey named `api_key` (or
        override api_key_field).
        """
        url = "/api/ogimage/presets/"
        response = await self._client.post(url, json=data.model_dump(mode="json", exclude_unset=True, exclude_none=True))
        if not response.is_success:
            try:
                error_body = response.json()
            except Exception:
                error_body = response.text
            msg = f"{response.status_code}: {error_body}"
            raise httpx.HTTPStatusError(
                msg, request=response.request, response=response
            )
        return OGImagePreset.model_validate(response.json())


    async def presets_retrieve(self, id: str) -> OGImagePreset:
        """
        Mixin for ViewSets that need to filter by API key ownership. Provides
        consistent queryset filtering across apps: - Superusers see all records
        - Test API key in dev mode: see all records (like superuser) - API key
        auth: filter by api_key - User auth: filter by api_key__user Usage:
        class MyViewSet(SDKAPIKeyFilterMixin, viewsets.ModelViewSet): queryset =
        MyModel.objects.all() api_key_field = "api_key" # FK field name
        (default) The model must have a FK to SDKAPIKey named `api_key` (or
        override api_key_field).
        """
        url = f"/api/ogimage/presets/{id}/"
        response = await self._client.get(url)
        if not response.is_success:
            try:
                error_body = response.json()
            except Exception:
                error_body = response.text
            msg = f"{response.status_code}: {error_body}"
            raise httpx.HTTPStatusError(
                msg, request=response.request, response=response
            )
        return OGImagePreset.model_validate(response.json())


    async def presets_update(self, id: str, data: OGImagePresetRequest) -> OGImagePreset:
        """
        Mixin for ViewSets that need to filter by API key ownership. Provides
        consistent queryset filtering across apps: - Superusers see all records
        - Test API key in dev mode: see all records (like superuser) - API key
        auth: filter by api_key - User auth: filter by api_key__user Usage:
        class MyViewSet(SDKAPIKeyFilterMixin, viewsets.ModelViewSet): queryset =
        MyModel.objects.all() api_key_field = "api_key" # FK field name
        (default) The model must have a FK to SDKAPIKey named `api_key` (or
        override api_key_field).
        """
        url = f"/api/ogimage/presets/{id}/"
        response = await self._client.put(url, json=data.model_dump(mode="json", exclude_unset=True, exclude_none=True))
        if not response.is_success:
            try:
                error_body = response.json()
            except Exception:
                error_body = response.text
            msg = f"{response.status_code}: {error_body}"
            raise httpx.HTTPStatusError(
                msg, request=response.request, response=response
            )
        return OGImagePreset.model_validate(response.json())


    async def presets_partial_update(
        self,
        id: str,
        data: PatchedOGImagePresetRequest | None = None,
    ) -> OGImagePreset:
        """
        Mixin for ViewSets that need to filter by API key ownership. Provides
        consistent queryset filtering across apps: - Superusers see all records
        - Test API key in dev mode: see all records (like superuser) - API key
        auth: filter by api_key - User auth: filter by api_key__user Usage:
        class MyViewSet(SDKAPIKeyFilterMixin, viewsets.ModelViewSet): queryset =
        MyModel.objects.all() api_key_field = "api_key" # FK field name
        (default) The model must have a FK to SDKAPIKey named `api_key` (or
        override api_key_field).
        """
        url = f"/api/ogimage/presets/{id}/"
        _json = data.model_dump(mode="json", exclude_unset=True, exclude_none=True) if data else None
        response = await self._client.patch(url, json=_json)
        if not response.is_success:
            try:
                error_body = response.json()
            except Exception:
                error_body = response.text
            msg = f"{response.status_code}: {error_body}"
            raise httpx.HTTPStatusError(
                msg, request=response.request, response=response
            )
        return OGImagePreset.model_validate(response.json())


    async def presets_destroy(self, id: str) -> None:
        """
        Mixin for ViewSets that need to filter by API key ownership. Provides
        consistent queryset filtering across apps: - Superusers see all records
        - Test API key in dev mode: see all records (like superuser) - API key
        auth: filter by api_key - User auth: filter by api_key__user Usage:
        class MyViewSet(SDKAPIKeyFilterMixin, viewsets.ModelViewSet): queryset =
        MyModel.objects.all() api_key_field = "api_key" # FK field name
        (default) The model must have a FK to SDKAPIKey named `api_key` (or
        override api_key_field).
        """
        url = f"/api/ogimage/presets/{id}/"
        response = await self._client.delete(url)
        if not response.is_success:
            try:
                error_body = response.json()
            except Exception:
                error_body = response.text
            msg = f"{response.status_code}: {error_body}"
            raise httpx.HTTPStatusError(
                msg, request=response.request, response=response
            )
        return None


