import os

from django.core.asgi import get_asgi_application

# Fetch Django's ASGI application early to ensure the AppRegistry is populated
# before importing code that may import ORM models.
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.local") # Use local settings for ASGI
django_asgi_app = get_asgi_application()

from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter

from smoothschedule.commerce.tickets import routing as tickets_routing
from smoothschedule.scheduling.schedule import routing as schedule_routing
from smoothschedule.commerce.tickets.middleware import TokenAuthMiddleware


application = ProtocolTypeRouter(
    {
        "http": django_asgi_app,
        "websocket": AuthMiddlewareStack(
            TokenAuthMiddleware(
                URLRouter(
                    tickets_routing.websocket_urlpatterns +
                    schedule_routing.websocket_urlpatterns
                )
            )
        ),
    }
)