"""
Helpers shared by every chat-sending code path.
"""

import logging

from asgiref.sync import async_to_sync
from channels.layers import get_channel_layer

logger = logging.getLogger(__name__)


def broadcast_new_message(message):
    """
    Push a newly-created Message to any open WebSocket connections in its
    room, live.

    The WebSocket consumer's own handle_message() already broadcasts
    messages sent *through* the socket itself. But the app's actual "Send"
    button on every chat screen calls the REST send-message endpoints
    (teacher/parent/student), not the socket — those endpoints only ever
    saved the Message row and returned it in the HTTP response, with
    nothing pushed to the recipient's open connection. That's why messages
    only appeared for the other person after they manually refreshed
    (their next REST poll/refetch), never live.

    Call this once, right after Message.objects.create(...), from every
    REST send-message view — it's the direct fix for that gap.
    """
    try:
        channel_layer = get_channel_layer()
        if not channel_layer:
            return

        from .serializers import MessageSerializer

        message_data = MessageSerializer(message).data
        async_to_sync(channel_layer.group_send)(
            f"chat_{message.room_id}",
            {
                "type": "chat_message",
                "message": message_data,
                "sender_type": message.sender_type,
                "sender_id": message.sender_id,
            },
        )
    except Exception as e:
        logger.error(f"Failed to broadcast message {message.id}: {e}")
