# core/asgi.py
import os
from django.core.asgi import get_asgi_application

# ✅ Set settings module FIRST
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings')

# ✅ Initialize Django ASGI application FIRST (this loads Django apps)
django_asgi_app = get_asgi_application()

# ✅ Now import channel stuff AFTER Django is initialized
from channels.routing import ProtocolTypeRouter, URLRouter
from django.urls import path

# ✅ Import consumer/middleware after Django apps are loaded
from chat.consumers import ChatConsumer
from chat.ws_auth import JWTAuthMiddleware

application = ProtocolTypeRouter({
    "http": django_asgi_app,
    # JWTAuthMiddleware resolves the connecting teacher/parent/student from
    # the ?token= JWT itself (see chat/ws_auth.py) — django.contrib.auth's
    # AuthMiddlewareStack is session-cookie based and does nothing useful
    # for this JWT-authenticated app, so it's replaced rather than layered.
    "websocket": JWTAuthMiddleware(
        URLRouter([
            path('ws/chat/<uuid:room_id>/', ChatConsumer.as_asgi()),
        ])
    ),
})