"""DMS-specific realtime room helpers and publish functions.

Room naming
-----------
All DMS room names use underscores (not colons) so they are valid as
channel layer group names without transformation in the Channels backend.

  dms_doc_{public_id}        — live updates for a single document
  dms_comments_{public_id}   — comment feed for a document
  dms_user_{user_pk}         — per-user DMS notification stream

The ``MemoryRealtimeBackend`` (used in tests) and the
``ChannelsRealtimeBackend`` (used in production) both receive these
room strings via the common ``publish(room, event, payload)`` interface.
"""

from __future__ import annotations

from typing import Any

from simorgh.core.realtime import get_backend


# ---------------------------------------------------------------------------
# Room name helpers
# ---------------------------------------------------------------------------

def document_room(public_id: str) -> str:
    """WebSocket room for live document updates (presence, version changes)."""
    return f"dms_doc_{public_id}"


def comments_room(public_id: str) -> str:
    """WebSocket room for realtime comment feed on a document."""
    return f"dms_comments_{public_id}"


def user_notifications_room(user_pk: int) -> str:
    """WebSocket room for per-user DMS notification stream."""
    return f"dms_user_{user_pk}"


# ---------------------------------------------------------------------------
# Convenience publish functions
# ---------------------------------------------------------------------------

def publish_document_event(public_id: str, event: str, payload: dict[str, Any]) -> None:
    """Broadcast a document lifecycle event to all subscribers."""
    get_backend().publish(document_room(str(public_id)), event, payload)


def publish_comment_event(public_id: str, event: str, payload: dict[str, Any]) -> None:
    """Broadcast a comment feed event to all subscribers."""
    get_backend().publish(comments_room(str(public_id)), event, payload)


def publish_user_notification(user_pk: int, event: str, payload: dict[str, Any]) -> None:
    """Broadcast a DMS notification to a specific user."""
    get_backend().publish(user_notifications_room(user_pk), event, payload)


__all__ = [
    "comments_room",
    "document_room",
    "publish_comment_event",
    "publish_document_event",
    "publish_user_notification",
    "user_notifications_room",
]
