import os
from django.core.asgi import get_asgi_application
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.security.websocket import AllowedHostsOriginValidator

# 1. Initialize Django's settings and ASGI app first.
# This ensures the AppRegistry (where models/apps live) is fully populated.
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "lariv.settings")
django_asgi_app = get_asgi_application()

# 2. Import ALL Channels-related components *after* Django setup.
# This includes your custom middleware and the urlpatterns.
from channels.auth import AuthMiddlewareStack
from .urls import websocket_urlpatterns


application = ProtocolTypeRouter(
    {
        # Explicitly use the pre-initialized Django ASGI app for HTTP
        "http": django_asgi_app,
        "websocket": AllowedHostsOriginValidator(
            AuthMiddlewareStack(URLRouter(websocket_urlpatterns))
        ),
    }
)
