from __future__ import annotations

import httpx

from .models import (
    OGImageManagedCreateRequest,
    OGImageManagedRegenerateResponse,
    OGImageManagedResponse,
    PatchedOGImageManagedPatchRequest,
)


class OgimageManagedAPI:
    """API endpoints for Ogimage Managed."""

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

    async def create(self, data: OGImageManagedCreateRequest) -> OGImageManagedResponse:
        """
        Create managed LLM OG image

        POST /api/ogimage/managed/ — create entry and enqueue LLM generation.
        """
        url = "/api/ogimage/managed/"
        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 OGImageManagedResponse.model_validate(response.json())


    async def retrieve(self, slug: str) -> OGImageManagedResponse:
        """
        Get managed OG image status

        GET /api/ogimage/managed/{slug}/
        """
        url = f"/api/ogimage/managed/{slug}/"
        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 OGImageManagedResponse.model_validate(response.json())


    async def partial_update(
        self,
        slug: str,
        data: PatchedOGImageManagedPatchRequest | None = None,
    ) -> OGImageManagedResponse:
        """
        Update managed OG image metadata

        PATCH /api/ogimage/managed/{slug}/ — update metadata, no
        auto-regeneration.
        """
        url = f"/api/ogimage/managed/{slug}/"
        _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 OGImageManagedResponse.model_validate(response.json())


    async def destroy(self, slug: str) -> None:
        """
        Delete managed OG image

        DELETE /api/ogimage/managed/{slug}/
        """
        url = f"/api/ogimage/managed/{slug}/"
        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


    async def regenerate_create(self, slug: str) -> OGImageManagedRegenerateResponse:
        """
        Re-enqueue managed OG image generation

        POST /api/ogimage/managed/{slug}/regenerate/ — reset and re-enqueue.
        """
        url = f"/api/ogimage/managed/{slug}/regenerate/"
        response = await self._client.post(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 OGImageManagedRegenerateResponse.model_validate(response.json())


