"""Command for undoing the last conversation turn."""

from dataclasses import dataclass

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

from cli.tui.chat.commands.base import CommandResult
from cli.tui.chat.types import extract_message_text


@dataclass
class UndoResult:
    """Result data for undo operation.

    Attributes:
        user_preview: Preview of the undone user message.
    """

    user_preview: str


@dataclass
class UndoCommand:
    """Command to undo the last conversation turn.

    This marks both the last user message and assistant response as
    excluded from context, effectively removing them from the conversation.

    Attributes:
        client: Server client for API calls.
        user_message: The user message to exclude.
        assistant_message: The assistant message to exclude.
    """

    client: ApiClient
    user_message: MessageResponse
    assistant_message: MessageResponse

    async def execute(self) -> CommandResult[UndoResult]:
        """Execute the undo operation.

        Returns:
            CommandResult with preview of undone message on success.
        """
        try:
            # Mark both messages as excluded from context
            for msg in [self.user_message, self.assistant_message]:
                await self.client.update_message(
                    msg.id, UpdateMessageRequest(include_in_context=False)
                )

            # Get preview text for user feedback
            user_text = extract_message_text(self.user_message)
            user_preview = user_text

            return CommandResult[UndoResult](
                success=True,
                data=UndoResult(user_preview=user_preview),
            )

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