from pydantic import BaseModel, Field
from sinapsis_core.data_containers.data_packet import DataContainer

from sinapsis_chat_history.helpers.schemas import ChatHistoryFilters
from sinapsis_chat_history.templates.chat_history_base import (
    ChatHistoryBase,
    ChatHistoryBaseAttributes,
)


class ChatHistoryDeleteArgs(BaseModel):
    """Arguments for deleting chat history messages.

    Attributes:
        user_id (str): Required explicit user scope for deletion.
        session_id (str | None): Optional explicit session scope for deletion.
        filters (ChatHistoryFilters): Optional message-level filters applied in
            addition to the resolved scope.
    """

    user_id: str
    session_id: str | None = None
    filters: ChatHistoryFilters = Field(default_factory=ChatHistoryFilters)


class ChatHistoryDelete(ChatHistoryBase):
    """Template for deleting chat history records from a storage backend.

    Usage example:
    agent:
      name: my_test_agent
    templates:
    - template_name: InputTemplate
      class_name: InputTemplate
      attributes: {}
    - template_name: ChatHistoryDelete
      class_name: ChatHistoryDelete
      template_input: InputTemplate
      attributes:
        provider: sqlite
        db_config:
          db_path: "chat_history.sqlite3"
          table: "chat"
        delete_args:
          user_id: "Sarah"
          session_id: "conv_1234"
          filters:
            role: assistant
    """

    class AttributesBaseModel(ChatHistoryBaseAttributes):
        """Attributes for configuring how chat history is deleted.

        Attributes:
            delete_args (ChatHistoryDeleteArgs): Scope and filter options used
                when deleting stored messages.
        """

        delete_args: ChatHistoryDeleteArgs

    def execute(self, container: DataContainer) -> DataContainer:
        """Delete chat messages that match the configured scope and filters.

        Args:
            container (DataContainer): Incoming container, unused by the
                deletion logic.

        Returns:
            DataContainer: The same container passed in, unmodified.
        """
        message = self.db.remove_messages(**self.attributes.delete_args.model_dump(exclude_none=True))
        self.logger.info(message)

        return container
