"""Message data structure."""

import json
from dataclasses import dataclass
from typing import Dict, Any, Optional, TYPE_CHECKING

from .conversation import Conversation
from .conversation_client import ConversationClient

if TYPE_CHECKING:
    from .memory import Memory
    from .memory_client import MemoryClient


@dataclass
class Message:
    """Represents an incoming message."""

    content: str
    conversation_id: str
    user_id: str
    headers: Dict[str, str]
    raw_body: Dict[str, Any]
    conversation: Optional[Conversation] = None
    memory: Optional["Memory"] = None
    metadata: Optional[Dict[str, Any]] = None
    schema: Optional[Dict[str, Any]] = None

    @classmethod
    def from_kafka_message(
        cls,
        body: Dict[str, Any],
        headers: Dict[str, str],
        conversation_client: Optional[ConversationClient] = None,
        memory_client: Optional["MemoryClient"] = None,
        agent_name: Optional[str] = None,
    ):
        """Create Message from Kafka message."""
        from .memory import Memory

        conversation_id = headers.get("conversationId")
        user_id = headers.get("userId", "anonymous")

        # Parse metadata from header
        metadata = None
        metadata_header = headers.get("messageMetadata")
        if metadata_header:
            try:
                metadata = json.loads(metadata_header)
            except json.JSONDecodeError:
                pass

        # Parse schema from header
        schema = None
        schema_header = headers.get("messageSchema")
        if schema_header:
            try:
                schema = json.loads(schema_header)
            except json.JSONDecodeError:
                pass

        conversation = None
        if conversation_id and conversation_client:
            conversation = Conversation(conversation_id, conversation_client, agent_name)

        memory = None
        if memory_client and user_id and conversation_id:
            memory = Memory(user_id, conversation_id, memory_client)

        return cls(
            content=body.get("content", ""),
            conversation_id=conversation_id,
            user_id=user_id,
            headers=headers,
            raw_body=body,
            conversation=conversation,
            memory=memory,
            metadata=metadata,
            schema=schema,
        )
