"""
Django settings for ptcoffee project.

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

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/
"""

import os
import socket
import logging.config
import sentry_sdk
from pathlib import Path
from environs import Env
from dotenv import load_dotenv, find_dotenv
from django.urls import reverse_lazy
from sentry_sdk.integrations.django import DjangoIntegration


env = Env()
load_dotenv(find_dotenv())

# 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.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = env(
    'SECRET_KEY',
    'django-insecure-xexy-3e8&9p13&r&*yhsbk0_s1x#58i1(q#&^p!fn10hz$g43f'
)

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

ALLOWED_HOSTS = env.list('ALLOWED_HOSTS', ['*'])

INTERNAL_IPS = ['127.0.0.1', '10.0.2.2' '172.27.0.4']

if DEBUG:
    hostname, _, ips = socket.gethostbyname_ex(socket.gethostname())
    INTERNAL_IPS += [ip[: ip.rfind('.')] + '.1' for ip in ips]


def show_toolbar(request):
    return True


if DEBUG:
    DEBUG_TOOLBAR_CONFIG = {
        'SHOW_TOOLBAR_CALLBACK': 'ptcoffee.settings.show_toolbar',
    }


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.sites',

    # 3rd Party
    'django_filters',
    'storages',
    'localflavor',
    'django_celery_beat',
    'django_celery_results',
    'anymail',
    'compressor',
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'analytical',

    # Local
    'accounts.apps.AccountsConfig',
    'core.apps.CoreConfig',
    'dashboard.apps.DashboardConfig',
    'storefront.apps.StorefrontConfig',
]

MIDDLEWARE = [
    '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',
    'ptcoffee.middleware.TimezoneMiddleware',
    'ptcoffee.middleware.RestrictStaffToAdminMiddleware',
]

if DEBUG:
    INSTALLED_APPS + ['debug_toolbar']
    MIDDLEWARE + ['debug_toolbar.middleware.DebugToolbarMiddleware']


ROOT_URLCONF = 'ptcoffee.urls'
LOGIN_REDIRECT_URL = reverse_lazy('storefront:product-list')

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / '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',
                'core.context_processors.site_settings',
                'storefront.context_processors.cart',
                'storefront.context_processors.product_categories',
            ],
        },
    },
]

WSGI_APPLICATION = 'ptcoffee.wsgi.application'


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

DATABASES = {
    'default': {
        'ENGINE': env('DB_ENGINE', 'django.db.backends.sqlite3'),
        'NAME': env('POSTGRES_DB', BASE_DIR / 'db.sqlite3'),
        'USER': env('POSTGRES_USER', ''),
        'PASSWORD': env('POSTGRES_PASSWORD', ''),
        'HOST': env('DB_HOST', ''),
        'PORT': env.int('DB_PORT', ''),
    }
}


# Cache
# https://docs.djangoproject.com/en/4.1/ref/settings/#caches

CACHE = {
    'default': {
        'BACKEND': env('CACHE_BACKEND'),
        'LOCATION': env('CACHE_LOCATION'),
    }
}


# Sessions
# https://docs.djangoproject.com/en/4.1/ref/settings/#sessions

SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db'
SESSION_COOKIE_SECURE = env.bool('SESSION_COOKIE_SECURE', False)


# Site
# https://docs.djangoproject.com/en/4.1/ref/settings/#sites

SITE_ID = 1
SECURE_HSTS_SECONDS = env.int('SECURE_HSTS_SECONDS', 3600)
SECURE_SSL_REDIRECT = env.bool('SECURE_SSL_REDIRECT', False)
CSRF_COOKIE_SECURE = env.bool('CSRF_COOKIE_SECURE', False)
SECURE_CROSS_ORIGIN_OPENER_POLICY = 'same-origin-allow-popups'
FILE_UPLOAD_MAX_MEMORY_SIZE = 60000000
CSRF_TRUSTED_ORIGINS = env.list(
    'CSRF_TRUSTED_ORIGINS',
    ['https://ptcoffee-dev.windmillapps.org']
)


# 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',
    },
]

AUTHENTICATION_BACKENDS = [
    'django.contrib.auth.backends.ModelBackend',
    'allauth.account.auth_backends.AuthenticationBackend',
]

AUTH_USER_MODEL = 'accounts.User'


# All-auth
# https://django-allauth.readthedocs.io/en/latest/installation.html

ACCOUNT_FORMS = {'signup': 'accounts.forms.UserSignupForm'}
ACCOUNT_ADAPTER = 'accounts.adapter.AccountAdapter'
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_SIGNUP_PASSWORD_ENTER_TWICE = True
ACCOUNT_SESSION_REMEMBER = True
ACCOUNT_UNIQUE_EMAIL = True


# Internationalization
# https://docs.djangoproject.com/en/4.1/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.1/howto/static-files/

STATIC_URL = 'static/'
STATIC_ROOT = '/var/www/static/'
MEDIA_URL = 'media/'
MEDIA_ROOT = '/var/www/media'
STATICFILES_DIRS = [BASE_DIR / 'static']
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.1/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'


# Celery
# https://docs.celeryq.dev/en/stable/django/first-steps-with-django.html

CELERY_BROKER_URL = CACHE['default']['LOCATION']
CELERY_RESULT_BACKEND = CELERY_BROKER_URL
CELERY_CACHE_BACKEND = CELERY_BROKER_URL
CELERY_ACCEPT_CONTENT = ['json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TASK_TRACK_STARTED = True
CELERY_TIMEZONE = 'US/Mountain'


# Facebook Pixel
# https://www.facebook.com/gpa/blog/the-facebook-pixel

FACEBOOK_PIXEL_ID = env('FACEBOOK_PIXEL_ID', '')


# Stripe
# https://stripe.com/docs

STRIPE_API_KEY = env('STRIPE_API_KEY')
STRIPE_WEBHOOK_SECRET = env('STRIPE_WEBHOOK_SECRET', None)


# PayPal
# https://developer.paypal.com/docs/checkout/advanced/integrate

PAYPAL_CLIENT_ID = env('PAYPAL_CLIENT_ID')
PAYPAL_SECRET_ID = env('PAYPAL_SECRET_ID')
PAYPAL_ENVIRONMENT = env('PAYPAL_ENVIRONMENT', 'SANDBOX')


# Email
# https://anymail.dev/en/v9.0/installation/#installing-anymail

EMAIL_BACKEND = 'anymail.backends.mailgun.EmailBackend'
TEMPLATED_EMAIL_BACKEND = 'templated_email.backends.vanilla_django.TemplateBackend'
DEFAULT_FROM_EMAIL = env('DEFAULT_FROM_EMAIL', 'webmaster@localhost')
SERVER_EMAIL = env('SERVER_EMAIL', 'root@localhost')

ANYMAIL = {
    'MAILGUN_API_KEY': env('MAILGUN_API_KEY'),
    'MAILGUN_SENDER_DOMAIN': env('MAILGUN_SENDER_DOMAIN')
}

ADMINS = env.list('ADMINS', [('Nathan Chapman', 'debug@nathanjchapman.com')])
MANAGERS = ADMINS


# Currency

DEFAULT_COUNTRY = 'US'
DEFAULT_CURRENCY = 'USD'
DEFAULT_DECIMAL_PLACES = 2
DEFAULT_MAX_DIGITS = 12
DEFAULT_CURRENCY_CODE_LENGTH = 3


# Logging
# https://docs.djangoproject.com/en/4.1/topics/logging/

if not DEBUG:
    LOGGING_CONFIG = None
    logging.config.dictConfig({
        'version': 1,
        'disable_existing_loggers': False,
        'formatters': {
            'console': {
                'format': '[%(asctime)s %(levelname)s %(name)s:%(lineno)s] %(module)s %(process)d %(thread)d %(message)s',
            },
        },
        'handlers': {
            'console': {
                'class': 'logging.StreamHandler',
                'formatter': 'console',
            },
        },
        'loggers': {
            '': {
                'level': 'DEBUG',
                'handlers': ['console'],
            },
        },
    })


# Sentry
# https://docs.sentry.io/platforms/python/guides/django/

SENTRY_DSN = env('SENTRY_DSN', '')
SENTRY_ENV = env('SENTRY_ENV', 'development')

if not DEBUG:
    sentry_sdk.init(
        dsn=SENTRY_DSN,
        environment=SENTRY_ENV,
        integrations=[DjangoIntegration()],

        # Set traces_sample_rate to 1.0 to capture 100%
        # of transactions for performance monitoring.
        # We recommend adjusting this value in production.
        traces_sample_rate=1.0,

        # If you wish to associate users to errors (assuming you are using
        # django.contrib.auth) you may enable sending PII data.
        send_default_pii=True
    )
