import logging
from os import getenv
from pathlib import Path

EVIBES_VERSION = "2.8.5"

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

SECRET_KEY = getenv("SECRET_KEY")
DEBUG = bool(int(getenv("DEBUG")))

ALLOWED_HOSTS = {
    "app:8000",
    "worker:8000",
    "beat:8000",
    "localhost:8000",
    "api.localhost:8000",
    "b2b.localhost:8000",
    "127.0.0.1:8000",
    "api.127.0.0.1:8000",
    "b2b.127.0.0.1:8000",
}

if DEBUG:
    ALLOWED_HOSTS.add("*")
else:
    for entry in getenv("ALLOWED_HOSTS").split(" "):
        ALLOWED_HOSTS.add(entry)

ALLOWED_HOSTS = tuple(ALLOWED_HOSTS)

CSRF_TRUSTED_ORIGINS = {
    "http://127.0.0.1",
    "http://api.localhost",
    "http://b2b.localhost",
}

for entry in getenv("CSRF_TRUSTED_ORIGINS").split(" "):
    CSRF_TRUSTED_ORIGINS.add(entry)

CSRF_TRUSTED_ORIGINS = tuple(CSRF_TRUSTED_ORIGINS)

if DEBUG:
    CORS_ALLOW_ALL_ORIGINS = True
else:
    CORS_ALLOWED_ORIGINS = {
        "http://127.0.0.1",
        "http://api.localhost",
        "http://b2b.localhost",
    }
    for entry in getenv("CORS_ALLOWED_ORIGINS").split(" "):
        CORS_ALLOWED_ORIGINS.add(entry)

    CORS_ALLOWED_ORIGINS = tuple(CORS_ALLOWED_ORIGINS)

    CORS_ALLOW_METHODS = (
        "DELETE",
        "GET",
        "OPTIONS",
        "PATCH",
        "POST",
        "PUT",
    )

CORS_ALLOW_HEADERS = (
    "accept",
    "accept-encoding",
    "accept-language",
    "content-type",
    "connection",
    "user-agent",
    "authorization",
    "host",
    "x-csrftoken",
    "x-requested-with",
    "x-evibes-auth",
    "baggage",
    "sentry-trace",
    "dnt",
    "sec-fetch-dest",
    "sec-fetch-mode",
    "sec-fetch-site",
    "sec-gpc",
    "origin",
    "referer",
)

USE_X_FORWARDED_HOST = True
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https") if not DEBUG else None
X_FRAME_OPTIONS = "SAMEORIGIN"

UNSAFE_CACHE_KEYS = []

SITE_ID = 1

INSTALLED_APPS = [
    "django_prometheus",
    "constance",
    "django_daisy",
    "modeltranslation",
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "django.contrib.sitemaps",
    "django.contrib.gis",
    "django.contrib.humanize",
    "health_check",
    "health_check.db",
    "health_check.cache",
    "health_check.storage",
    "health_check.contrib.migrations",
    "health_check.contrib.celery",
    "health_check.contrib.celery_ping",
    "health_check.contrib.psutil",
    "health_check.contrib.redis",
    "health_check.contrib.db_heartbeat",
    "cacheops",
    "django_hosts",
    "django_celery_beat",
    "django_celery_results",
    "django_extensions",
    "django_redis",
    "widget_tweaks",
    "mptt",
    "rest_framework",
    "rest_framework_simplejwt",
    "rest_framework_simplejwt.token_blacklist",
    "drf_spectacular",
    "drf_spectacular_sidecar",
    "django_json_widget",
    "django_elasticsearch_dsl",
    "dbbackup",
    "corsheaders",
    "constance.backends.database",
    "django_mailbox",
    "graphene_django",
    "core",
    "payments",
    "vibes_auth",
    "blog",
]

MIDDLEWARE = [
    "evibes.middleware.BlockInvalidHostMiddleware",
    "django_prometheus.middleware.PrometheusBeforeMiddleware",
    "django_hosts.middleware.HostsRequestMiddleware",
    "django.middleware.security.SecurityMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "corsheaders.middleware.CorsMiddleware",
    "evibes.middleware.CustomCommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
    "evibes.middleware.CustomLocaleMiddleware",
    "django_hosts.middleware.HostsResponseMiddleware",
    "djangorestframework_camel_case.middleware.CamelCaseMiddleWare",
    "django_prometheus.middleware.PrometheusAfterMiddleware",
]

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [
            BASE_DIR / "vibes_auth/templates",
            BASE_DIR / "core/templates",
            BASE_DIR / "payments/templates",
        ],
        "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",
            ],
        },
    },
]

USE_I18N = True

LANGUAGES = (
    ("en-gb", "English (British)"),
    ("ar-ar", "العربية"),
    ("cs-cz", "Česky"),
    ("da-dk", "Dansk"),
    ("de-de", "Deutsch"),
    ("en-us", "English (American)"),
    ("es-es", "Español"),
    ("fr-fr", "Français"),
    ("hi-in", "हिंदी"),
    ("it-it", "Italiano"),
    ("ja-jp", "日本語"),
    ("kk-kz", "Қазақ"),
    ("nl-nl", "Nederlands"),
    ("pl-pl", "Polska"),
    ("pt-br", "Português"),
    ("ro-ro", "Română"),
    ("ru-ru", "Русский"),
    ("zh-hans", "简体中文"),
)

LANGUAGE_CODE = "en-gb"

CURRENCIES = (
    ("en-gb", "EUR"),
    ("ar-ar", "AED"),
    ("cs-cz", "CZK"),
    ("da-dk", "EUR"),
    ("de-de", "EUR"),
    ("en-us", "USD"),
    ("es-es", "EUR"),
    ("fr-fr", "EUR"),
    ("hi-in", "INR"),
    ("it-it", "EUR"),
    ("ja-jp", "JPY"),
    ("kk-kz", "KZT"),
    ("nl-nl", "EUR"),
    ("pl-pl", "PLN"),
    ("pt-br", "EUR"),
    ("ro-ro", "RON"),
    ("ru-ru", "RUB"),
    ("zh-hans", "CNY"),
)

CURRENCY_CODE = dict(CURRENCIES).get(LANGUAGE_CODE)

MODELTRANSLATION_FALLBACK_LANGUAGES = (LANGUAGE_CODE, "en-us", "de-de")

ROOT_URLCONF = "evibes.urls"

WSGI_APPLICATION = "evibes.wsgi.application"

ASGI_APPLICATION = "evibes.asgi.application"

DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

TIME_ZONE = getenv("TIME_ZONE", "Europe/London")

STATIC_URL = f"https://api.{getenv('EVIBES_BASE_DOMAIN')}/static/"
STATIC_ROOT = BASE_DIR / "static"

MEDIA_URL = f"https://api.{getenv('EVIBES_BASE_DOMAIN')}/media/"
MEDIA_ROOT = BASE_DIR / "media"

AUTH_USER_MODEL = "vibes_auth.User"

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

APPEND_SLASH = True

ROOT_HOSTCONF = "evibes.hosts"
DEFAULT_HOST = "api"
REDIS_PASSWORD = getenv("REDIS_PASSWORD", default="")

INTERNAL_IPS = [
    "127.0.0.1",
]

DAISY_SETTINGS = {
    "SITE_LOGO": "/static/favicon.ico",
    "EXTRA_STYLES": [],
    "EXTRA_SCRIPTS": [],
    "LOAD_FULL_STYLES": True,
    "SHOW_CHANGELIST_FILTER": True,
    "DONT_SUPPORT_ME": True,
    "SIDEBAR_FOOTNOTE": "eVibes by Wiseless",
    "APPS_REORDER": {
        "django_celery_beat": {
            "icon": "fa fa-solid fa-timeline",
            "hide": False,
            "app": "django_celery_beat",
            "priority": 0,
            "apps": "",
        },
        "django_mailbox": {
            "icon": "fa fa-solid fa-envelope",
            "hide": False,
            "app": "django_mailbox",
            "priority": 1,
            "apps": "",
        },
        "payments": {
            "icon": "fa fa-solid fa-wallet",
            "hide": False,
            "app": "payments",
            "priority": 2,
            "apps": "",
        },
        "blog": {
            "icon": "fa fa-solid fa-book",
            "hide": False,
            "app": "blog",
            "priority": 3,
            "apps": "",
        },
        "core": {
            "icon": "fa fa-solid fa-house",
            "hide": False,
            "app": "core",
            "priority": 4,
            "apps": "",
        },
        "vibes_auth": {
            "icon": "fa fa-solid fa-user",
            "hide": False,
            "app": "vibes_auth",
            "priority": 5,
            "apps": "",
        },
    },
}

if getenv("SENTRY_DSN"):
    import sentry_sdk
    from sentry_sdk.integrations.celery import CeleryIntegration
    from sentry_sdk.integrations.django import DjangoIntegration
    from sentry_sdk.integrations.logging import LoggingIntegration
    from sentry_sdk.integrations.redis import RedisIntegration

    ignore_errors = [
        "django.http.response.Http404",
        "django.core.exceptions.PermissionDenied",
        "django.core.exceptions.BadRequest",
        "billiard.exceptions.SoftTimeLimitExceeded",
        "core.models.Attribute.DoesNotExist",
        "core.models.AttributeGroup.DoesNotExist",
        "core.models.AttributeValue.DoesNotExist",
        "core.models.Product.DoesNotExist",
        "core.models.Category.DoesNotExist",
        "core.models.Brand.DoesNotExist",
        "core.models.Stock.DoesNotExist",
        "core.models.ProductImage.DoesNotExist",
        "blog.models.Post.DoesNotExist",
    ]

    if DEBUG:
        ignore_errors.extend(["billiard.exceptions.WorkerLostError", "billiard.exceptions.TimeLimitExceeded"])

    sentry_sdk.init(
        dsn=getenv("SENTRY_DSN"),
        traces_sample_rate=1.0 if DEBUG else 0.2,
        profiles_sample_rate=1.0 if DEBUG else 0.1,
        integrations=[
            DjangoIntegration(),
            LoggingIntegration(level=logging.INFO, event_level=logging.ERROR),
            CeleryIntegration(),
            RedisIntegration(),
        ],
        environment="development" if DEBUG else "production",
        debug=False,
        release=f"evibes@{EVIBES_VERSION}",
        ignore_errors=ignore_errors,
    )

SESSION_COOKIE_HTTPONLY = True
CSRF_COOKIE_HTTPONLY = True
LANGUAGE_COOKIE_HTTPONLY = True

DATA_UPLOAD_MAX_NUMBER_FIELDS = 8888

ADMINS = [("Egor Gorbunov", "contact@fureunoir.com")]

STORAGES = {
    "default": {
        "BACKEND": "django.core.files.storage.FileSystemStorage",
    },
    "staticfiles": {
        "BACKEND": "django.contrib.staticfiles.storage.StaticFilesStorage",
    },
    "dbbackup": {
        "BACKEND": "django.core.files.storage.FileSystemStorage",
    },
}
