"""Command for reloading the current session's messages."""

from dataclasses import dataclass
from uuid import UUID

from alloy_runtime_sdk.api_client.client import ApiClient
from alloy_runtime_types.dtos.sessions import MessageResponse

from cli.tui.chat.commands.base import CommandResult
from cli.tui.chat.store import ChatStore


@dataclass
class ReloadSessionResult:
    """Result data for reload session operation.

    Attributes:
        messages: Updated list of messages.
    """

    messages: list[MessageResponse]


@dataclass
class ReloadSessionCommand:
    """Command to reload the current session's messages.

    This is a lightweight operation that only fetches messages,
    without changing the session context. Useful after sending
    a message or regenerating to get the updated message list.

    Attributes:
        client: Server client for API calls.
        store: Chat store for state management.
        session_id: ID of the session to reload.
        message_limit: Maximum number of messages to fetch.
    """

    client: ApiClient
    store: ChatStore
    session_id: UUID
    message_limit: int = 100

    async def execute(self) -> CommandResult[ReloadSessionResult]:
        """Execute the reload session operation.

        Returns:
            CommandResult with updated messages on success.
        """
        try:
            session = await self.client.get_session(
                self.session_id, limit=self.message_limit
            )
            self.store.set_messages(list(session.messages))

            return CommandResult[ReloadSessionResult](
                success=True,
                data=ReloadSessionResult(messages=list(session.messages)),
            )

        except Exception as e:
            return CommandResult[ReloadSessionResult](success=False, error=str(e))
