"""
Django settings for config project (Django 4.2 LTS).

Everything environment-specific is read from a `.env` file next to manage.py
(see .env.example). Local development can run on SQLite with DB_ENGINE=sqlite.
"""
import os
from pathlib import Path

from dotenv import load_dotenv

BASE_DIR = Path(__file__).resolve().parent.parent
load_dotenv(BASE_DIR / '.env')


def env_bool(name, default=False):
    return os.environ.get(name, str(default)).strip().lower() in ('1', 'true', 'yes', 'on')


def env_list(name, default=''):
    return [v.strip() for v in os.environ.get(name, default).split(',') if v.strip()]


SECRET_KEY = os.environ.get(
    'SECRET_KEY',
    'django-insecure-tz@x8&&9$68%r1_&m3mq#57hz*9)szmjpa=z6nxv!7kcb#4%51',
)

DEBUG = env_bool('DEBUG', False)

ALLOWED_HOSTS = env_list('ALLOWED_HOSTS', 'localhost,127.0.0.1')
CSRF_TRUSTED_ORIGINS = env_list('CSRF_TRUSTED_ORIGINS', '')

# The app is served over plain HTTP on the IP (no domain / TLS yet), so auth
# cookies must not be "Secure" or the browser drops them. Set to True once
# the site is behind HTTPS.
AUTH_COOKIE_SECURE = env_bool('AUTH_COOKIE_SECURE', False)


# Application definition

INSTALLED_APPS = [
    # No 'django.contrib.admin' and no 'django.contrib.sessions':
    # login uses a JWT cookie (see NexusApp/jwt_auth.py), not sessions.
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'NexusApp',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
    'NexusApp.middleware.LowercasePrefixMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'NexusApp.jwt_auth.JWTAuthMiddleware',        # sets request.user from the JWT cookie
    'NexusApp.jwt_auth.StaffJWTAuthMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
# Page protection is done per route in NexusApp/urls.py with
# auth_required / guest_only (see NexusApp/middleware.py).

ROOT_URLCONF = 'config.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

# Key used to encrypt staff passwords (admin can view them). Generate with:
#   python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"
STAFF_FERNET_KEY = os.environ.get("STAFF_FERNET_KEY")


WSGI_APPLICATION = 'config.wsgi.application'

# Matches migration 0002_alter_adminuser_id (AutoField)
DEFAULT_AUTO_FIELD = 'django.db.models.AutoField'


# Database

if os.environ.get('DB_ENGINE', 'mysql').lower() == 'sqlite':
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': BASE_DIR / os.environ.get('SQLITE_NAME', 'db.sqlite3'),
        }
    }
else:
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME': os.environ.get('DATABASE_NAME', 'nexus_db'),
            'USER': os.environ.get('DATABASE_USER', 'root'),
            'PASSWORD': os.environ.get('DATABASE_PASSWORD', ''),
            'HOST': os.environ.get('DATABASE_HOST', '127.0.0.1'),
            'PORT': os.environ.get('DATABASE_PORT', '3306'),
            'OPTIONS': {
                'charset': 'utf8mb4',
                'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",
            },
        }
    }


# Password validation

AUTH_PASSWORD_VALIDATORS = [
    {'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator'},
    {'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator'},
    {'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator'},
    {'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator'},
]


# Internationalization

LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Kolkata'
USE_I18N = True
USE_TZ = True


# Static files

STATIC_URL = '/static/'
STATIC_ROOT = BASE_DIR / 'staticfiles'

STATICFILES_DIRS = [
    BASE_DIR / 'NexusApp' / 'static',
]

# Uploaded files (Aadhaar photos)
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'

DATA_UPLOAD_MAX_MEMORY_SIZE = 5 * 1024 * 1024
FILE_UPLOAD_MAX_MEMORY_SIZE = 5 * 1024 * 1024


# Flash messages stored in a cookie (no session needed)
# CSRF token also uses a cookie by default (no session needed)
MESSAGE_STORAGE = 'django.contrib.messages.storage.cookie.CookieStorage'


# Email (prints emails/OTPs in the terminal)

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'


# Logging (SQL query spam goes to the file only, not the terminal)

os.makedirs(BASE_DIR / 'logs', exist_ok=True)

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,

    'formatters': {
        'verbose': {
            'format': '{levelname} {asctime} {name} {message}',
            'style': '{',
        },
    },

    'handlers': {
        'file': {
            'level': 'INFO',
            'class': 'logging.FileHandler',
            'filename': BASE_DIR / 'logs' / 'django.log',
            'formatter': 'verbose',
        },
        'console': {
            'level': 'INFO',
            'class': 'logging.StreamHandler',
        },
    },

    'loggers': {
        'django': {
            'handlers': ['file', 'console'],
            'level': 'INFO',
            'propagate': False,
        },
        'django.db.backends': {
            'handlers': ['file'],
            'level': 'WARNING',
            'propagate': False,
        },
    },

    'root': {
        'handlers': ['file', 'console'],
        'level': 'INFO',
    },
}