"""
Django settings for app project.

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

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

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

import os
from pathlib import Path

TRUE_VALUES = {"1", "true", "yes", "on"}

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

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
# MOVED TO local_settings.py

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    "core",
    "django.contrib.admin",
    # 'core.apps.LibraryAdminConfig', # our custom OTP'ed admin
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "django_htmx",
    "crispy_forms",
    "crispy_bulma",
    # "django_tables2",
    # "django_tables2_bulma_template",
    "django_otp",
    "django_otp.plugins.otp_totp",
    # "django_otp.plugins.otp_email",
    # 'django_otp.plugins.otp_hotp',
    "django_otp.plugins.otp_static",
    "two_factor",
    # "two_factor.plugins.phonenumber",
    # "two_factor.plugins.email",
    # "two_factor.plugins.yubikey",
    # "otp_yubikey",
    "mixins",
    "cachalot",
]

DEBUG_TOOLBAR_ENABLED = os.getenv("DEBUG_TOOLBAR_ENABLED", "false").lower() in TRUE_VALUES

if DEBUG_TOOLBAR_ENABLED:
    INSTALLED_APPS.extend(
        [
            "debug_toolbar",
            "template_profiler_panel",
        ]
    )

# Performance optimisations
CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        # "LOCATION": "unix:///var/run/socks/redis.sock",
        # "LOCATION": f"redis://{REDIS_HOST}:{REDIS_PORT}",
        "LOCATION": "unix:///var/run/gia-redis.sock",
        "OPTIONS": {
            "db": 10,
            # "parser_class": "django_redis.cache.RedisCache",
            # "PASSWORD": REDIS_PASSWORD,
            "pool_class": "redis.BlockingConnectionPool",
        },
    }
}
# CACHE_MIDDLEWARE_ALIAS = 'default'
# CACHE_MIDDLEWARE_SECONDS = '600'
# CACHE_MIDDLEWARE_KEY_PREFIX = ''

CRISPY_TEMPLATE_PACK = "bulma"
CRISPY_ALLOWED_TEMPLATE_PACKS = ("bulma",)
DJANGO_TABLES2_TEMPLATE = "django-tables2/bulma.html"

MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    # 'django.middleware.cache.UpdateCacheMiddleware',
    "django.middleware.common.CommonMiddleware",
    # 'django.middleware.cache.FetchFromCacheMiddleware',
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django_otp.middleware.OTPMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
    "django_htmx.middleware.HtmxMiddleware",
]

if DEBUG_TOOLBAR_ENABLED:
    MIDDLEWARE.insert(0, "debug_toolbar.middleware.DebugToolbarMiddleware")

ROOT_URLCONF = "app.urls"
ASGI_APPLICATION = "app.asgi.application"
COMPOSE_WS_ENABLED = os.environ.get("COMPOSE_WS_ENABLED", "false").lower() in {
    "1",
    "true",
    "yes",
    "on",
}

TEMPLATE_CONTEXT_PROCESSORS = [
    "django.template.context_processors.request",
    "django.contrib.auth.context_processors.auth",
    "django.contrib.messages.context_processors.messages",
    "core.util.django_settings_export.settings_export",
    "core.context_processors.settings_hierarchy_nav",
]

if DEBUG_TOOLBAR_ENABLED:
    TEMPLATE_CONTEXT_PROCESSORS.insert(0, "django.template.context_processors.debug")

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [os.path.join(BASE_DIR, "core/templates")],
        "APP_DIRS": True,
        "OPTIONS": {
            "context_processors": TEMPLATE_CONTEXT_PROCESSORS,
        },
    },
]

WSGI_APPLICATION = "app.wsgi.application"


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

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.sqlite3",
        "NAME": os.getenv("APP_DATABASE_PATH", "/conf/db.sqlite3"),
    }
}


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

AUTH_PASSWORD_VALIDATORS = [
    {"NAME": f"django.contrib.auth.password_validation.{name}"}
    for name in [
        "UserAttributeSimilarityValidator",
        "MinimumLengthValidator",
        "CommonPasswordValidator",
        "NumericPasswordValidator",
    ]
]


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

LANGUAGE_CODE = "en-us"

TIME_ZONE = "UTC"

USE_I18N = True

USE_TZ = True


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

STATIC_URL = "static/"

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

DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

AUTH_USER_MODEL = "core.User"

LOGIN_REDIRECT_URL = "home"
LOGOUT_REDIRECT_URL = "home"
# 2FA
LOGIN_URL = "two_factor:login"
# LOGIN_REDIRECT_URL = 'two_factor:profile'

# ALLOWED_PAYMENT_METHODS = ["bacs_debit", "card"]
ALLOWED_PAYMENT_METHODS = ["card"]

REST_FRAMEWORK = {
    "DEFAULT_PARSER_CLASSES": [
        "rest_framework.parsers.JSONParser",
    ]
}

INTERNAL_IPS = [
    item.strip()
    for item in os.getenv("INTERNAL_IPS", "localhost").split(",")
    if item.strip()
]

DEBUG_TOOLBAR_PANELS = [
    "template_profiler_panel.panels.template.TemplateProfilerPanel",
    "debug_toolbar.panels.history.HistoryPanel",
    "debug_toolbar.panels.versions.VersionsPanel",
    "debug_toolbar.panels.timer.TimerPanel",
    "debug_toolbar.panels.settings.SettingsPanel",
    "debug_toolbar.panels.headers.HeadersPanel",
    "debug_toolbar.panels.request.RequestPanel",
    "debug_toolbar.panels.sql.SQLPanel",
    "debug_toolbar.panels.staticfiles.StaticFilesPanel",
    "debug_toolbar.panels.templates.TemplatesPanel",
    "debug_toolbar.panels.cache.CachePanel",
    "debug_toolbar.panels.signals.SignalsPanel",
    "debug_toolbar.panels.logging.LoggingPanel",
    "debug_toolbar.panels.redirects.RedirectsPanel",
    "debug_toolbar.panels.profiling.ProfilingPanel",
    # "cachalot.panels.CachalotPanel",  # Disabled due to compatibility issues with debug toolbar
]

from app.local_settings import *  # noqa

if PROFILER:  # noqa - trust me its there
    import pyroscope

    pyroscope.configure(
        application_name="neptune",
        server_address="http://pyroscope:4040",
        auth_token=os.getenv("PYROSCOPE_AUTH_TOKEN", ""),
        # tags           = {
        #     "region":   f'{os.getenv("REGION")}',
        # }
    )


def show_toolbar(request):
    return DEBUG and DEBUG_TOOLBAR_ENABLED  # noqa: from local imports


DEBUG_TOOLBAR_CONFIG = {
    "SHOW_TOOLBAR_CALLBACK": show_toolbar,
}
