from typing import Any

from pydantic import Field
from sinapsis_core.template_base.base_models import (
    OutputTypes,
    TemplateAttributes,
    TemplateAttributeType,
    UIPropertiesMetadata,
)
from sinapsis_core.template_base.template import Template

from sinapsis_chat_history.helpers.schemas import ProviderName
from sinapsis_chat_history.helpers.tags import Tags
from sinapsis_chat_history.providers.factory import StorageProviderFactory


class ChatHistoryBaseAttributes(TemplateAttributes):
    """Shared attributes for chat history templates.

    Attributes:
        provider (ProviderName): The storage backend to use.
        db_config (dict[str, Any]): Raw provider configuration dictionary.
    """

    provider: ProviderName = "sqlite"
    db_config: dict[str, Any] = Field(default_factory=dict)


class ChatHistoryBase(Template):
    """Base class for chat history templates."""

    AttributesBaseModel = ChatHistoryBaseAttributes
    UIProperties = UIPropertiesMetadata(
        category="Chat History", output_type=OutputTypes.TEXT, tags=[Tags.CHATBOTS, Tags.CHAT_HISTORY, Tags.CONTEXT]
    )

    def __init__(self, attributes: TemplateAttributeType) -> None:
        """Initialize the template and configured chat history provider.

        Args:
            attributes (TemplateAttributeType): Raw template attributes used to
                configure the selected provider.
        """
        super().__init__(attributes)
        self.db = StorageProviderFactory.create(provider=self.attributes.provider, config=self.attributes.db_config)
