"""
Django settings for the project.

Generated by 'django-admin startproject' using Django.

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

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

import os
from datetime import timedelta
from pathlib import Path

from django.contrib.messages import constants as messages
from django.utils.translation import gettext_lazy as _

from apps.shop.enums import PaymentGateway

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

# Build paths inside the project like this: BASE_DIR / 'subdir'.

BASE_DIR = Path(__file__).resolve().parent.parent.parent

# General

DEBUG = True
SECRET_KEY = "myapp-secret-key"
IS_INSIDE_CI = os.getenv("CI") == "true"

# Hosts

ALLOWED_HOSTS = ["*"]

csrf_trusted_origins = os.getenv("APP_CSRF_TRUSTED_ORIGINS")
if csrf_trusted_origins:
    CSRF_TRUSTED_ORIGINS = csrf_trusted_origins.split(",")

allowed_hosts = os.getenv("APP_ALLOWED_HOSTS")
if allowed_hosts:
    ALLOWED_HOSTS = allowed_hosts.split(",")

# Application definition

DJANGO_APPS = [
    "pyaa.apps.AppAdminConfig",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.humanize",
    "django.contrib.sessions",
    "django.contrib.sitemaps",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "django.contrib.sites",
    "django.forms",
]

THIRD_PARTY_APPS = [
    "django_admin_extras",
    "django_cleanup.apps.CleanupConfig",
    "tinymce",
    "corsheaders",
    "widget_tweaks",
    "cache_cleaner",
    "django_recaptcha",
    "rangefilter",
    "django_admin_listfilter_dropdown",
    "django_q",
    "django_translation_flags",
    "localflavor",
]

PROJECT_APPS = [
    "apps.backup",
    "apps.web.apps.WebAppConfig",
    "apps.api.apps.ApiAppConfig",
    "apps.site.apps.SiteAppConfig",
    "apps.user.apps.UserAppConfig",
    "apps.report.apps.ReportAppConfig",
    "apps.customer.apps.CustomerAppConfig",
    "apps.system_log.apps.SystemLogAppConfig",
    "apps.language.apps.LanguageAppConfig",
    "apps.content.apps.ContentAppConfig",
    "apps.gallery.apps.GalleryAppConfig",
    "apps.shop.apps.ShopAppConfig",
    "apps.banner.apps.BannerAppConfig",
    "apps.newsletter.apps.NewsletterAppConfig",
]

INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + PROJECT_APPS

MIDDLEWARE = [
    "corsheaders.middleware.CorsMiddleware",
    "django.middleware.security.SecurityMiddleware",
    "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.middleware.locale.LocaleMiddleware",
]

ROOT_URLCONF = "pyaa.urls"

# WSGI
# https://fastapi.tiangolo.com/advanced/wsgi/
WSGI_APPLICATION = "pyaa.wsgi.application"

# Template
# https://docs.djangoproject.com/en/6.0/topics/templates/
DJANGO_TEMPLATE_DIRS = [
    BASE_DIR / "templates",
]

DJANGO_TEMPLATE_LOADERS_DEV = [
    "django.template.loaders.filesystem.Loader",
    "django.template.loaders.app_directories.Loader",
]

DJANGO_TEMPLATE_LOADERS_PROD = [
    (
        "django.template.loaders.cached.Loader",
        DJANGO_TEMPLATE_LOADERS_DEV,
    )
]

DJANGO_TEMPLATE_LOADERS = (
    DJANGO_TEMPLATE_LOADERS_DEV if DEBUG else DJANGO_TEMPLATE_LOADERS_PROD
)

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": DJANGO_TEMPLATE_DIRS,
        "APP_DIRS": False,
        "OPTIONS": {
            "debug": DEBUG,
            "loaders": DJANGO_TEMPLATE_LOADERS,
            "context_processors": [
                "django.template.context_processors.debug",
                "django.template.context_processors.request",
                "django.contrib.auth.context_processors.auth",
                "django.contrib.messages.context_processors.messages",
                "pyaa.context_processors.site_processor",
                "pyaa.context_processors.cookie_consent_processor",
            ],
        },
    },
]

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

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.sqlite3",
        "NAME": BASE_DIR / "db" / "db.sqlite3",
        "TEST": {
            "NAME": BASE_DIR / "db" / "db-test.sqlite3",
        },
    }
}

# Cache
# https://docs.djangoproject.com/en/6.0/topics/cache/
# https://www.honeybadger.io/blog/caching-in-django/

CACHES = {
    "default": {
        "BACKEND": "django.core.cache.backends.dummy.DummyCache",
    },
}

# Password validation
# https://docs.djangoproject.com/en/6.0/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/6.0/topics/i18n/

LANGUAGE_CODE = "en-us"
TIME_ZONE = "UTC"
USE_I18N = True
USE_TZ = True

LANGUAGES = [
    ("en", _("language.en")),
    ("pt-br", _("language.pt-br")),
]

LOCALE_PATHS = [
    BASE_DIR / "locale",
]

DEFAULT_TIME_ZONE = "America/Sao_Paulo"

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

STATIC_URL = "/static/"
STATIC_ROOT = BASE_DIR / "static"

STATICFILES_DIRS = [
    BASE_DIR / "apps" / "web" / "static",
]

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

# Messages

MESSAGE_TAGS = {
    messages.DEBUG: "alert-info",
    messages.INFO: "alert-info",
    messages.SUCCESS: "alert-success",
    messages.WARNING: "alert-warning",
    messages.ERROR: "alert-error",
}

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

DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

# JWT

AUTH_JWT = {
    "ACCESS_TOKEN_LIFETIME": timedelta(days=365 * 999),
    "REFRESH_TOKEN_LIFETIME": timedelta(days=365 * 999),
    "SIGNING_KEY": SECRET_KEY,
    "ALGORITHM": "HS256",
}

# Storage

STORAGES = {
    "default": {
        "BACKEND": "django.core.files.storage.FileSystemStorage",
    },
    "staticfiles": {
        "BACKEND": "django.contrib.staticfiles.storage.StaticFilesStorage",
    },
    "s3": {
        "BACKEND": "storages.backends.s3.S3Storage",
        "OPTIONS": {
            "access_key": os.getenv("AWS_ACCESS_KEY_ID"),
            "secret_key": os.getenv("AWS_SECRET_ACCESS_KEY"),
            "bucket_name": os.getenv("AWS_S3_BUCKET_NAME"),
            "region_name": os.getenv("AWS_REGION"),
            "default_acl": "public-read",
            "querystring_auth": False,
        },
    },
}

# Media

MEDIA_URL = os.getenv("APP_MEDIA_URL", "/media/")
MEDIA_ROOT = BASE_DIR / "media"

# Editor

UPLOAD_PATH = "uploads"

TINYMCE_DEFAULT_CONFIG = {
    "height": "400px",
    "width": "100%",
    "menubar": True,
    "plugins": "advlist autolink lists link image charmap preview anchor searchreplace visualblocks code fullscreen insertdatetime media table code help wordcount",
    "toolbar": "undo redo | bold italic underline strikethrough | fontselect fontsizeselect formatselect | alignleft aligncenter alignright alignjustify | outdent indent | numlist bullist checklist | forecolor backcolor casechange permanentpen formatpainter removeformat | pagebreak | insertfile image media pageembed template link anchor codesample | charmap emoticons | fullscreen preview save print | a11ycheck ltr rtl | showcomments addcomment code",
    "custom_undo_redo_levels": 10,
    "images_upload_url": "/upload-image/",
    "relative_urls": False,
    "remove_script_host": False,
    "convert_urls": True,
    "valid_elements": "*[*]",
}

# CORS

CORS_ALLOW_ALL_ORIGINS = True

# Site

SITE_ID = 1

# Authentication

AUTHENTICATION_BACKENDS = ("apps.user.backends.MultiFieldModelBackend",)

LOGIN_REDIRECT_URL = "home"

AUTH_USER_MODEL = "user.User"

LOGIN_URL = "account_login"

PASSWORD_RECOVERY_TOKEN_TTL = timedelta(hours=1)

LOGIN_RATELIMIT_MAX_ATTEMPTS = 10
LOGIN_RATELIMIT_WINDOW = 300

# Email

EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
DEFAULT_FROM_EMAIL = "webmaster@localhost"
DEFAULT_TO_EMAIL = "webmaster@localhost"

# Logging

LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "formatters": {
        "verbose": {
            "format": "{levelname} {asctime} {module} {message}",
            "style": "{",
        },
    },
    "handlers": {
        "file": {
            "level": "DEBUG",
            "class": "logging.FileHandler",
            "filename": BASE_DIR / "logs" / "debug.log",
            "formatter": "verbose",
        },
    },
    "root": {
        "handlers": ["file"],
        "level": "DEBUG",
    },
}

# Customer

CUSTOMER_SIGNUP_PLAN = 0
CUSTOMER_ACTIVATION_REQUIRED = False

# Stripe

STRIPE_SECRET_KEY = os.getenv("STRIPE_SECRET_KEY", "")
STRIPE_WEBHOOK_SECRET = os.getenv("STRIPE_WEBHOOK_SECRET", "")

# Recaptcha

RECAPTCHA_PUBLIC_KEY = os.getenv("RECAPTCHA_PUBLIC_KEY", "")
RECAPTCHA_PRIVATE_KEY = os.getenv("RECAPTCHA_PRIVATE_KEY", "")

# Django Q

Q_CLUSTER = {
    "name": "djangoq",  # name of the cluster for identification
    "workers": 4,  # number of worker processes handling tasks (reduce if using a low-resource server)
    "recycle": 500,  # number of tasks a worker processes before being replaced (helps prevent memory leaks)
    "timeout": 600,  # maximum execution time (in seconds) for a task before being terminated
    "retry": 600,  # delay (in seconds) before retrying a failed task
    "max_attempts": 2,  # maximum number of retry attempts for failed tasks
    "bulk": 20,  # number of tasks fetched from the database at once (reduces db queries)
    "orm": "default",  # defines the orm for job persistence (default database in django settings)
}

# Gateway

GATEWAY_FOR_PRODUCT_PURCHASE = PaymentGateway.STRIPE

# Banner
BANNER_ACCESS_INTERVAL = 86400  # 1 day in seconds

# Google Analytics

GOOGLE_ANALYTICS_ID = os.getenv("APP_GOOGLE_ANALYTICS_ID", "")

# Cookie Consent

COOKIE_CONSENT_VERSION = "1"

# System Log

SYSTEM_LOG_API_ENABLED = True
SYSTEM_LOG_WEBHOOK_ENABLED = False

# PyAA

PYAA_API_PREFIX = os.getenv("APP_API_PREFIX", "/api")
PYAA_ENABLE_FASTAPI = os.getenv("APP_ENABLE_FASTAPI", "true").lower() == "true"
PYAA_ENABLE_DJANGO = os.getenv("APP_ENABLE_DJANGO", "true").lower() == "true"
