#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys

from dotenv import load_dotenv


def main():
    """Run administrative tasks."""
    # THIS LINE HAS TO COME BEFORE THE setdefault BELOW, and the order is the
    # whole point of it being here at all.
    #
    # `.env` is otherwise read by settings/base.py, which is imported only
    # AFTER the settings module has already been chosen by the setdefault — so
    # a `DJANGO_SETTINGS_MODULE` line in `.env` could never win, and on the
    # cPanel box `manage.py migrate` silently ran under `development`. That is
    # SQLite: it created a db.sqlite3 in the application root, reported every
    # migration as applied, and left the MySQL schema empty. Nothing failed,
    # and the first sign of it was /admin/ answering 500 while the API — which
    # rejects a missing token without ever touching the database — looked fine.
    #
    # `load_dotenv()` does not override a variable already in the environment,
    # so an explicit `DJANGO_SETTINGS_MODULE=... manage.py ...` still wins over
    # `.env`, and `.env` still wins over the development default below.
    load_dotenv()

    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings.development')
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    execute_from_command_line(sys.argv)


if __name__ == '__main__':
    main()
