from __future__ import annotations

from typing import TYPE_CHECKING, Any

from ...._endpoints import Characters
from ...._internal._builders.characters import build_character_reply_recommend_body
from ...._internal._schemas import APIEnvelope
from ...._internal._schemas.characters.characters_replies import (
    CharacterReplyRecommend,
    RecommendMessage,
)
from ...._utils import normalize_history
from ..._base import BaseResource

if TYPE_CHECKING:
    from ...._async_client import AsyncClient
    from ...._types import HistoryInput
else:
    AsyncClient = Any


class AsyncCharactersRepliesResource(BaseResource[AsyncClient]):
    """Provides AI-suggested reply recommendations for character chats (async).

    Accessible via ``client.characters.replies``.
    """

    async def recommend(
        self,
        character_id: str,
        *,
        char_name: str | None = None,
        character_type: int | None = None,
        user_name: str | None = None,
        messages: HistoryInput | None = None,
    ) -> APIEnvelope[CharacterReplyRecommend]:
        """Fetch suggested replies the user could send next.

        Returns a list of AI-generated text suggestions based on the
        current conversation context. Useful for surfacing "quick reply"
        options in a chat UI.

        Args:
            character_id: The character to generate suggestions for.
            char_name: Display name of the character. When ``None``, the
                server uses the character's configured name.
            character_type: Internal character type flag forwarded to the
                API.
            user_name: Display name of the user.
            messages: Recent conversation history used as context. Pass a
                ``ChatHistory`` from ``seaart.helpers`` (recommended) or
                any ``HistoryInput``-compatible value — see
                :meth:`~AsyncCharactersMessagesResource.stream` for the
                full list of accepted formats.

        Returns:
            ``APIEnvelope[CharacterReplyRecommend]`` — ``.value.items`` is
            a list of suggestions, each with a ``.text`` field.
            ``.value.free_times`` is the number of free recommendations
            remaining.

        Example:
            >>> from seaart.helpers import ChatHistory
            >>> history = ChatHistory().user("Hello!").ai("Hi. How are you?")
            >>> result = await client.characters.replies.recommend(
            ...     "char_abc123", messages=history
            ... )
            >>> for suggestion in result.value.items or []:
            ...     print(suggestion.text)
        """
        recommend_msgs: list[RecommendMessage] | None = None
        if messages is not None:
            recommend_msgs = [
                RecommendMessage(
                    role="user" if msg.role == 1 else "assistant",
                    text=msg.content,
                )
                for msg in reversed(
                    normalize_history(messages, ensure_last_assistant=False)
                )
            ]

        body = build_character_reply_recommend_body(
            character_id=character_id,
            char_name=char_name,
            character_type=character_type,
            user_name=user_name,
            messages=recommend_msgs,
        )
        env = await self._client.request_route(
            Characters.Replies.RECOMMEND,
            json=body.model_dump(exclude_none=True),
        )
        return APIEnvelope[CharacterReplyRecommend].model_validate(env)
