import json
import uuid
import time
from dataclasses import dataclass, field
from typing import Dict, Optional

@dataclass
class Message:
    """消息类，存放消息信息"""
    _id: str = field(default_factory=lambda: str(uuid.uuid4()))
    sender_id: str = ""                         # 发送编号
    sender_name: str = ""                       # 发送名称
    content: str = ""                           # 内容
    msg_type: str = "text"                      # 信息类
    timestamp: int = field(default_factory=lambda: int(time.time()*1000))
    reply_to: Optional[str] = None              # 回复给
    room_id: str = ""                           # 房间编号
    metadata: Dict = field(default_factory=dict)  # 其余信息
    
    
    def to_dict(self) -> dict:
        """转为字典类"""
        return {
            "_id": self._id,
            "sender_id": self.sender_id,
            "sender_name": self.sender_name,
            "content": self.content,
            "msg_type": self.msg_type,
            "timestamp": self.timestamp,
            "reply_to": self.reply_to,
            "room_id": self.room_id,
            "metadata": self.metadata
        }
        
        
    @classmethod
    def from_dict(cls, data: dict) -> "Message":
        """从字典创建类对象"""
        return cls(
            _id=data.get("_id", str(uuid.uuid4())),
            sender_id=data.get("sender_id", ""),
            sender_name=data.get("sender_name", ""),
            content=data.get("content", ""),
            msg_type=data.get("msg_type", "text"),
            timestamp=data.get("timestamp", int(time.time() * 1000)),
            reply_to=data.get("reply_to"),
            room_id=data.get("room_id", ""),
            metadata=data.get("metadata", {})
        )
        
    
    def reply(self, content: str, sender_id: str = "") -> "Message":
        """回复信息"""
        return Message(
            sender_id=sender_id,
            content=content,
            reply_to=self._id,
            room_id=self.room_id
        )
    
    def __repr__(self):
        """报告信息"""
        return f"Message({self.sender_name}: {self.content[:20]}...)"