import uuid
import json
from datetime import datetime
from typing import Dict, Any, Optional

class Message:
    """Message model for the message bus."""
    
    def __init__(self, 
                 message_topic: str, 
                 message_content: Any, 
                 message_properties: Optional[Dict[str, Any]] = None, 
                 message_id: Optional[str] = None, 
                 message_timestamp: Optional[datetime] = None, 
                 message_module: Optional[str] = None):
        self.message_id = message_id or str(uuid.uuid4())
        self.message_topic = message_topic
        self.message_content = message_content
        self.message_properties = message_properties or {}
        self.message_timestamp = message_timestamp or datetime.now()
        self.message_module = message_module
    
    def to_dict(self) -> Dict[str, Any]:
        """Convert message to dictionary."""
        return {
            'message_id': self.message_id,
            'message_topic': self.message_topic,
            'message_content': self.message_content,
            'message_properties': self.message_properties,
            'message_timestamp': self.message_timestamp.isoformat(),
            'message_module': self.message_module
        }
    
    def to_json(self) -> str:
        """Convert message to JSON string."""
        return json.dumps(self.to_dict(), ensure_ascii=False, indent=2)
    
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> 'Message':
        """Create message from dictionary."""
        return cls(
            message_id=data.get('message_id'),
            message_topic=data['message_topic'],
            message_content=data['message_content'],
            message_properties=data.get('message_properties', {}),
            message_timestamp=datetime.fromisoformat(data['message_timestamp']) if data.get('message_timestamp') else None,
            message_module=data.get('message_module')
        )
    
    @classmethod
    def from_json(cls, json_str: str) -> 'Message':
        """Create message from JSON string."""
        data = json.loads(json_str)
        return cls.from_dict(data)
