"""
WSGI config for main project.

It exposes the WSGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/2.0/howto/deployment/wsgi/
"""

import importlib
import io
import logging
import os

from django.core.wsgi import get_wsgi_application

logger = logging.getLogger()

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ocyan.main.settings")

application = get_wsgi_application()

# load spooler modules.
from ocyan.core.fender import config  # noqa: E402
from ocyan.core.plugins import get_spooler_mdodules  # noqa: E402

for spooler_module in get_spooler_mdodules():
    importlib.import_module(spooler_module)


from django.conf import settings  # noqa: E402

if not settings.DEBUG:
    # https://uwsgi-docs.readthedocs.io/en/latest/articles/TheArtOfGracefulReloading.html#dealing-with-ultra-lazy-apps-like-django
    # This issues a request to load the Django
    try:
        domain = config.get("django", "domain", "localhost")
        response = application(
            environ={
                "REQUEST_METHOD": "get",
                "REQUEST_URI": "/~startup/",
                "PATH_INFO": "/~startup/",
                "QUERY_STRING": "",
                "wsgi.input": io.StringIO(""),
                "SERVER_NAME": domain,
                "SERVER_PORT": 8000,
            },
            start_response=lambda x, y: None,
        )
        response.close()
    except Exception as exc:  # pylint: disable=W0703
        # Log this in case something went wrong here because of the fake request.
        logger.exception(exc)
