from os import getenv as os_getenv, path as os_path  # noqa
from pathlib import Path
from django.utils.translation import gettext_lazy as _

from django.core.management.utils import get_random_secret_key

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

SECRET_KEY = os_getenv(
    "SECRET_KEY", get_random_secret_key()
)  # If SECRET_KEY is not set, generate a random one
APP_ENV = os_getenv("APP_ENV", "dev")
DEBUG = os_getenv("DEBUG", "true").lower() in ["True", "true", "1", "yes", "y"]

ALLOWED_HOSTS = os_getenv("ALLOWED_HOSTS", "localhost").split(",")
if DEBUG:
    ALLOWED_HOSTS = ALLOWED_HOSTS + ['testserver']

if DEBUG:
    CSRF_TRUSTED_ORIGINS = os_getenv("CSRF_TRUSTED_ORIGINS", "http://localhost").split(
        ","
    )
    CORS_ORIGIN_ALLOW_ALL = True
else:
    CSRF_TRUSTED_ORIGINS = os_getenv("CSRF_TRUSTED_ORIGINS", "http://localhost").split(
        ","
    )
    CORS_ALLOWED_ORIGINS = os_getenv("CORS_ALLOWED_ORIGINS", "http://localhost").split(
        ","
    )

ADMINS = [tuple(a.split(',')) for a in os_getenv("ADMINS", "").split(";")]
MANAGERS = [tuple(a.split(',')) for a in os_getenv("MANAGERS", "").split(";")]
SERVER_EMAIL = os_getenv("SERVER_EMAIL", "")


# Application definition

INSTALLED_APPS = [
    "agenda_culturel",
    "django.contrib.admin",
    "django.contrib.sitemaps",
    "django.contrib.sites",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "corsheaders",
    "colorfield",
    "django_extensions",
    "django_better_admin_arrayfield",
    "django_filters",
    "compressor",
    "django_ckeditor_5",
    "recurrence",
    'django.contrib.gis',
    "location_field.apps.DefaultConfig",
    "django.contrib.postgres",
    "robots",
    "debug_toolbar",
    "cache_cleaner",
    "honeypot",
    "template_profiler_panel",
    'django_cleanup.apps.CleanupConfig',
    'django_unused_media',
]

HONEYPOT_FIELD_NAME = "alias_name"

MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "whitenoise.middleware.WhiteNoiseMiddleware",
    "django.middleware.common.BrokenLinkEmailsMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.locale.LocaleMiddleware",
    "corsheaders.middleware.CorsMiddleware",  # CorsMiddleware should be placed as high as possible,
    "django.middleware.common.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
    "debug_toolbar.middleware.DebugToolbarMiddleware", 
    'django.contrib.sites.middleware.CurrentSiteMiddleware',
#    "django.middleware.cache.UpdateCacheMiddleware",
#    "django.middleware.common.CommonMiddleware",
#    "django.middleware.cache.FetchFromCacheMiddleware",
]

CKEDITOR_5_CONFIGS = {
'default': {
      'toolbar': ['heading', '|', 'bold', 'italic', 'link', '|', 
                  'bulletedList', 'numberedList', 'blockQuote',], 
      'language': 'fr',
  },}

ROOT_URLCONF = "agenda_culturel.urls"

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [BASE_DIR / "templates"],
        "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",
            ],
            "loaders": [
                (
                    "django.template.loaders.cached.Loader",
                    [
                        "django.template.loaders.filesystem.Loader",
                        "django.template.loaders.app_directories.Loader",
                    ],
                ),
            ]
        },
    },
]

WSGI_APPLICATION = "agenda_culturel.wsgi.application"

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

DATABASES = {
    "default": {
        'ENGINE': 'django.contrib.gis.db.backends.postgis',
        "NAME": os_getenv("POSTGRES_DB", "postgres"),
        "USER": os_getenv("POSTGRES_USER", "postgres"),
        "PASSWORD": os_getenv("POSTGRES_PASSWORD", "postgres"),
        "HOST": os_getenv("POSTGRES_HOST", "db"),
        "PORT": os_getenv("POSTGRES_PORT", "5432"),
    }
}

# Password validation
# https://docs.djangoproject.com/en/4.2/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",
    },
]

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

LANGUAGE_CODE = "fr"

TIME_ZONE = "Europe/Paris"

USE_I18N = True

USE_TZ = False

LANGUAGES = (
    ("fr", _("French")),
)


# Auth

LOGIN_REDIRECT_URL = "/"

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

STATIC_URL = "static/"
STATIC_ROOT = os_path.join(BASE_DIR, "static")
MEDIA_URL = "media/"
MEDIA_ROOT = os_path.join(BASE_DIR, "media")

STATICFILES_FINDERS = [
    "django.contrib.staticfiles.finders.FileSystemFinder",
    "django.contrib.staticfiles.finders.AppDirectoriesFinder",
    "compressor.finders.CompressorFinder",
]

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

DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

# Redis
REDIS_DB_KEYS = {
    "dev": 0,
    "test": 1,
    "prod": 2,
}

# Redis settings

REDIS_HOST = os_getenv("REDIS_HOST", "redis")
REDIS_PORT = os_getenv("REDIS_PORT", 6379)

REDIS_DB = REDIS_DB_KEYS.get(APP_ENV, 0)
REDIS_URL = f"redis://{REDIS_HOST}:{REDIS_PORT}/{REDIS_DB}"

# Celery settings

CELERY_BROKER_URL = REDIS_URL
CELERY_RESULT_BACKEND = REDIS_URL

# SCSS
COMPRESS_PRECOMPILERS = (("text/x-scss", "django_libsass.SassCompiler"),)

# cache

CACHES = {
    "default": {
        "BACKEND": "django.core.cache.backends.redis.RedisCache",
        "LOCATION": REDIS_URL,
        "KEY_PREFIX": "agenda",
        "TIMEOUT": 60 * 15,
    }
}


# EMAIL settings

if os_getenv("EMAIL_BACKEND"):
    EMAIL_BACKEND = os_getenv("EMAIL_BACKEND")
    EMAIL_HOST = os_getenv("EMAIL_HOST")
    EMAIL_PORT = os_getenv("EMAIL_PORT")
    EMAIL_HOST_USER = os_getenv("EMAIL_HOST_USER")
    EMAIL_HOST_PASSWORD = os_getenv("EMAIL_HOST_PASSWORD")
    EMAIL_USE_TLS = os_getenv("EMAIL_USE_TLS", False)
    EMAIL_USE_SSL = os_getenv("EMAIL_USE_SSL", False)
    DEFAULT_FROM_EMAIL = os_getenv("DEFAULT_FROM_EMAIL")

# increase upload size for debug experiments
DATA_UPLOAD_MAX_MEMORY_SIZE = 10 * 2621440
DATA_UPLOAD_MAX_NUMBER_FIELDS = 10000

# recurrence translation

RECURRENCE_I18N_URL = "javascript-catalog"

# location field

LOCATION_FIELD = {
    "map.provider": "openstreetmap",
    "provider.openstreetmap.max_zoom": 18,
    "search.provider": "addok",
}

# stop robots

ROBOTS_USE_SITEMAP = False
ROBOTS_SITE_BY_REQUEST = 'cached-sitemap'

# debug
if DEBUG:
    import socket
    hostname, _, ips = socket.gethostbyname_ex(socket.gethostname())
    INTERNAL_IPS = [ip[: ip.rfind(".")] + ".1" for ip in ips] + ["127.0.0.1", "10.0.2.2"]

# logging

level_debug = "DEBUG" if DEBUG else "ERROR"
LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "handlers": {
        "file": {
            "level": level_debug,
            "class": "logging.FileHandler",
            "filename": "backend.log",
        },
        "mail_admins": {
            "level": "ERROR",
            "class": "django.utils.log.AdminEmailHandler",
            "include_html": True,
        },
    },
    "loggers": {
        "django": {
            "handlers": ["file"],
            "level": level_debug,
            "propagate": True,
        },
    },
}

# debug
DEBUG_TOOLBAR_PANELS = [
    '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.alerts.AlertsPanel',
    'debug_toolbar.panels.cache.CachePanel',
    'debug_toolbar.panels.signals.SignalsPanel',
    'debug_toolbar.panels.redirects.RedirectsPanel',
    'debug_toolbar.panels.profiling.ProfilingPanel',
    "template_profiler_panel.panels.template.TemplateProfilerPanel",
]


DJANGORESIZED_DEFAULT_SIZE = [1200, 1200]
DJANGORESIZED_DEFAULT_SCALE = 0.5
DJANGORESIZED_DEFAULT_QUALITY = 75
DJANGORESIZED_DEFAULT_KEEP_META = True
DJANGORESIZED_DEFAULT_FORCE_FORMAT = 'JPEG'
DJANGORESIZED_DEFAULT_FORMAT_EXTENSIONS = {'JPEG': ".jpg"}
DJANGORESIZED_DEFAULT_NORMALIZE_ROTATION = True