from datetime import datetime
from typing import Literal

from sqlalchemy import String, JSON, TEXT

from arclet.entari import MessageObject, MessageChain, Element
from entari_plugin_database import Base, Mapped, mapped_column  # entari: plugin


class MessageRecord(Base):
    __tablename__ = "entari_plugin_chronicle_messagerecord"
    __table_args__ = {"extend_existing": True}

    id: Mapped[int] = mapped_column(primary_key=True)
    user_id: Mapped[str] = mapped_column(String(64))
    """用户id"""
    channel_id: Mapped[str] = mapped_column(String(64), nullable=True)
    """频道id"""
    platform: Mapped[str] = mapped_column(String(32))
    """平台"""

    message_id: Mapped[str] = mapped_column(String(255))
    """消息id"""
    message: Mapped[dict] = mapped_column(JSON)
    """消息内容"""
    plain_text: Mapped[str] = mapped_column(TEXT)
    """消息内容的纯文本形式"""

    type: Mapped[Literal["message", "message_sent"]] = mapped_column(String(32))
    """消息类型"""
    time: Mapped[datetime]
    """消息时间"""

    def get_message(self) -> MessageChain[Element]:
        msg_obj = MessageObject.parse(self.message)
        return MessageChain(msg_obj.message)
