"""Event types for the message bus."""

from dataclasses import dataclass, field
from datetime import datetime
from typing import Any


@dataclass
class InboundAttachment:
    """Structured inbound attachment normalized by a channel."""

    file_id: str | None = None
    path: str | None = None
    url: str | None = None
    name: str | None = None
    mime_type: str | None = None
    size: int | None = None
    kind: str = "file"
    source: str = ""


@dataclass
class InboundMessage:
    """Message received from a chat channel."""

    channel: str  # telegram, discord, slack, whatsapp
    sender_id: str  # User identifier
    chat_id: str  # Chat/channel identifier
    content: str  # Message text
    timestamp: datetime = field(default_factory=datetime.now)
    media: list[str] = field(default_factory=list)  # Media URLs
    attachments: list[InboundAttachment] = field(default_factory=list)
    metadata: dict[str, Any] = field(default_factory=dict)  # Channel-specific data
    session_key_override: str | None = None  # Optional override for thread-scoped sessions

    @property
    def session_key(self) -> str:
        """Unique key for session identification."""
        return self.session_key_override or f"{self.channel}:{self.chat_id}"

    @property
    def media_paths(self) -> list[str]:
        """Normalized local media paths derived from attachments."""
        return [a.path for a in self.attachments if a.path]

    @property
    def media_urls(self) -> list[str]:
        """Normalized media URLs derived from attachments and legacy media list."""
        urls = [a.url for a in self.attachments if a.url]
        if urls:
            return urls
        return [m for m in self.media if isinstance(m, str) and m.strip()]

    @property
    def media_types(self) -> list[str]:
        """Normalized MIME types derived from attachments."""
        return [a.mime_type for a in self.attachments if a.mime_type]

    @property
    def media_path(self) -> str | None:
        """Primary local media path."""
        return self.media_paths[0] if self.media_paths else None

    @property
    def media_url(self) -> str | None:
        """Primary media URL."""
        return self.media_urls[0] if self.media_urls else None

    @property
    def media_type(self) -> str | None:
        """Primary media MIME type."""
        return self.media_types[0] if self.media_types else None


@dataclass
class OutboundMessage:
    """Message to send to a chat channel."""

    channel: str
    chat_id: str
    content: str
    reply_to: str | None = None
    media: list[str] = field(default_factory=list)
    metadata: dict[str, Any] = field(default_factory=dict)
    task_id: str | None = None  # Agent task identifier for frontend grouping
