"""Django settings for the diop_core project.

Generated by 'django-admin startproject' using Django 4.1.7.

For more information on this file, see
https://docs.djangoproject.com/en/4.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.1/ref/settings/
"""

# ruff: noqa: E501 (line length)
# ruff: noqa: F401 (imported but unused)

import os
from pathlib import Path

import ldap
from django_auth_ldap.config import LDAPSearch

import environ


# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

env = environ.Env(
    # set casting, default value
    DEBUG=(bool, False)
)
# the env file has to be set explicitly as an environment variable:
env.read_env(env.str("SETTINGS_ENV"))


SECRET_KEY = env.str("SECRET_KEY")

SITE_ID = 1


# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = env.bool("DEBUG")

# allowed hosts may be overridden in the private settings!
# having a pseudo-hostname here is handy during development (can be pointed to
# wherever using a corresponding entry in /etc/hosts)
ALLOWED_HOSTS = env.list(
    "ALLOWED_HOSTS", default=["127.0.0.1", "localhost", "diop.test"]
)

# required e.g. if running behind an nginx reverse proxy:
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")


# Application definition

INSTALLED_APPS = [
    "diop",
    "whitenoise.runserver_nostatic",
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.humanize",
    "django.contrib.sessions",
    "django.contrib.sites",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "django_q",
    "django_extensions",
]

MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "whitenoise.middleware.WhiteNoiseMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
    "django.contrib.sites.middleware.CurrentSiteMiddleware",
]

ROOT_URLCONF = "diop_core.urls"

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [],
        "APP_DIRS": True,
        "OPTIONS": {
            "context_processors": [
                "django.template.context_processors.debug",
                "django.template.context_processors.request",
                "django.contrib.auth.context_processors.auth",
                "django.contrib.messages.context_processors.messages",
            ],
        },
    },
]

WSGI_APPLICATION = "diop_core.wsgi.application"


# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases

DATABASES = {"default": env.db("DATABASE_URL")}


# Password validation
# https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators

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",
    },
]

LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "handlers": {"console": {"class": "logging.StreamHandler"}},
    "loggers": {"django_auth_ldap": {"level": "DEBUG", "handlers": ["console"]}},
}

AUTHENTICATION_BACKENDS = [
    "django.contrib.auth.backends.ModelBackend",
    "django_auth_ldap.backend.LDAPBackend",
]

AUTH_LDAP_BIND_DN = env.str("AUTH_LDAP_BIND_DN")
AUTH_LDAP_BIND_PASSWORD = env.str("AUTH_LDAP_BIND_PASSWORD")
AUTH_LDAP_SERVER_URI = env.str("AUTH_LDAP_SERVER_URI")
AUTH_LDAP_BASE_DN = env.str("AUTH_LDAP_BASE_DN")

AUTH_LDAP_CONNECTION_OPTIONS = {ldap.OPT_REFERRALS: 0}
AUTH_LDAP_USER_SEARCH = LDAPSearch(
    AUTH_LDAP_BASE_DN,
    ldap.SCOPE_SUBTREE,
    "sAMAccountName=%(user)s",
)
AUTH_LDAP_USER_ATTR_MAP = {
    "username": "sAMAccountName",
    "first_name": "givenName",
    "last_name": "sn",
    "email": "mail",
}

# Internationalization
# https://docs.djangoproject.com/en/4.1/topics/i18n/

LANGUAGE_CODE = "en-us"

DATE_FORMAT = "Y-m-d"
DATETIME_FORMAT = "Y-m-d H:i:s"

# Disable localized "L10N" formatting of data, otherwise the date and time
# formats defined above will be ignored / overridden.
# NOTE: Django 5.x will always have this set to True, currently it is unclear
# how this will play together with explicitly set date and time formats!
USE_L10N = False

TIME_ZONE = "Europe/Zurich"

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/

### REVIEW! ###
STATIC_URL = "static/"
STATIC_ROOT = BASE_DIR / "staticfiles"
STATICFILES_DIRS = [BASE_DIR / "diop" / "static"]
# STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"
STORAGES = {
    "staticfiles": {
        "BACKEND": "whitenoise.storage.CompressedManifestStaticFilesStorage",
    },
}


# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

CACHES = {
    "default": {
        "BACKEND": "django.core.cache.backends.db.DatabaseCache",
        "LOCATION": "django_diop_core_cache_table",
    }
}

# Email configuration
# https://docs.djangoproject.com/en/4.2/topics/email/
EMAIL_BACKEND = env.str("EMAIL_BACKEND")
EMAIL_HOST = env.str("EMAIL_HOST")


# django-q2 ORM broker connection
Q_CLUSTER = {
    "name": "DjangORM",
    "label": "Task Queue",
    "workers": 1,
    "timeout": 60,
    "retry": 120,
    "catch_up": False,
    "save_limit": 1000,
    "save_limit_per": "func",
    # "queue_limit": 50,
    # "bulk": 10,
    "orm": "default",
    "ALT_CLUSTERS": {
        "statusupdates": {
            "timeout": 30,
            "retry": 99999,
            "max_attempts": 1,
        },
        "housekeeping": {
            "timeout": 900,
            "retry": 99999,
            "workers": 2,
            "max_attempts": 1,
        },
        "activedirectory": {
            "timeout": 300,
            "retry": 600,
            "max_attempts": 4,
        },
        "ppms-short": {
            "timeout": 30,
            "retry": 120,
            "max_attempts": 4,
        },
        "ppms-long": {
            "timeout": 900,
            "retry": 1200,
            "max_attempts": 4,
        },
    },
}

PYPPMS_API_KEY = env.str("PYPPMS_API_KEY")
PYPPMS_URI = env.str("PYPPMS_URI")
PYPPMS_CACHE = env.str("PYPPMS_CACHE")
PYPPMS_CORE_REF = env.str("PYPPMS_CORE_REF")
PYPPMS_LOC_FILTER = env.str("PYPPMS_LOC_FILTER")
PYPPMS_NAME_GROUPS = env.list("PYPPMS_NAME_GROUPS")

DIOP_USER_AD_GROUP = env.str("DIOP_USER_AD_GROUP")
DIOP_SUPPORT_CONTACT = env.str("DIOP_SUPPORT_CONTACT")
DIOP_DISCONNECTED_MAX = env.int("DIOP_DISCONNECTED_MAX")
DIOP_NTDOMAIN = env.str("DIOP_NTDOMAIN")

# Switching on "graceful" mode will make several tasks run in a less impacting
# way, e.g. removing access to a DG will be done such that the standard group
# will still be allowed to connect. Most likely not useful in production!
DIOP_GRACEFUL = env.bool("DIOP_GRACEFUL")

# Switching on "dry-run" mode will prevent certain actions from doing effective
# changes to the platform, i.e. changing access permissions or terminating
# sessions. It will NOT affect components fetching status information to update
# the DB, or strictly informational effects like e-mails or pop-up messages
# (they will run normally). Actions that will be skipped due to dry-run being
# active will print a warning-level message to the log instead.
DIOP_DRY_RUN = env.bool("DIOP_DRY_RUN")
