from __future__ import annotations

from typing import TYPE_CHECKING, Any

from ..._endpoints import Images
from ..._internal._schemas import APIEnvelope
from ..._internal._schemas.history import (
    AddImageHistoryBody,
    Histories,
    ImageHistory,
)
from .._base import BaseResource

if TYPE_CHECKING:
    from ..._sync_client import SyncClient
else:
    SyncClient = Any


class HistoryResource(BaseResource[SyncClient]):
    """Manages the user's image usage history (sync).

    Accessible via ``client.images.history``.
    """

    def add(
        self,
        image_url: str,
        *,
        width: int | None = None,
        height: int | None = None,
        img_category: int = 2,
    ) -> APIEnvelope[None]:
        """Add an image to the user's history.

        Args:
            image_url: URL of the image to register.
            width: Image width in pixels.
            height: Image height in pixels.
            img_category: Image category flag forwarded to the API.

        Returns:
            ``APIEnvelope[None]`` — the server returns no data payload on
            success.

        Example:
            >>> client.images.history.add("https://cdn.example.com/img.jpg")
        """
        body = AddImageHistoryBody(
            url=image_url, width=width, height=height, img_category=img_category
        )
        return APIEnvelope[None].model_validate(
            self._client.request_route(
                Images.History.ADD,
                json=body.model_dump(exclude_none=True),
            )
        )

    def list(self, scene: str = "tf_v2") -> APIEnvelope[ImageHistory]:
        """Fetch the user's image history.

        Args:
            scene: Scene identifier forwarded to the API.

        Returns:
            ``APIEnvelope[ImageHistory]`` — ``.value.items`` is the list
            of history entries.

        Example:
            >>> result = client.images.history.list()
            >>> for item in result.value.items or []:
            ...     print(item.url)
        """
        env = self._client.request_route(
            Images.History.LIST,
            json={"scene": scene},
        )
        return APIEnvelope[ImageHistory].model_validate(env)

    def list_v2(  # TODO: clarify
        self,
        *,
        display_mode: int = 1,
        limit: int = 30,
        scene: str = "guest_task_item_count",
    ) -> APIEnvelope[Histories]:
        """Fetch the user's image history (v2 endpoint).

        Args:
            display_mode: Display mode flag forwarded to the API.
            limit: Maximum number of items to return.
            scene: Scene identifier forwarded to the API.

        Returns:
            ``APIEnvelope[Histories]`` — ``.value.items`` is the list of
            entries; ``.value.has_more`` indicates whether more pages exist;
            ``.value.after_id`` is the cursor for the next page.

        Example:
            >>> result = client.images.history.list_v2(limit=10)
            >>> for item in result.value.items or []:
            ...     print(item)
        """
        env = self._client.request_route(
            Images.History.LIST_V2,
            json={"display_mode": display_mode, "limit": limit, "scene": scene},
        )
        return APIEnvelope[Histories].model_validate(env)

    def delete(
        self,
        url: str,
    ) -> APIEnvelope[None]:
        """Delete an image entry from the user's history.

        Args:
            url: URL of the image entry to remove.

        Returns:
            ``APIEnvelope[None]`` — the server returns no data payload on
            success.

        Example:
            >>> client.images.history.delete("https://cdn.example.com/img.jpg")
        """
        return APIEnvelope[None].model_validate(
            self._client.request_route(
                Images.History.DELETE,
                json={"url": url},
            )
        )
