"""
Django settings for backend project.

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

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

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

import os
import json
import requests
import jwt

from cryptography.x509 import load_pem_x509_certificate
from cryptography.hazmat.backends import default_backend

from backend.read_env import read_env

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
SETTINGS_DIR = os.path.dirname(os.path.abspath(__file__))
BASE_DIR = os.path.dirname(SETTINGS_DIR)

# Get the docker secret
backend_secrets = read_env(os.environ.get("SECRETS_PATH"), "BACKEND_SECRETS")
social_provider_secrets = read_env(
    os.environ.get("SECRETS_PATH"), "SOCIAL_PROVIDER_SECRETS"
)
postgres_password = read_env(os.environ.get("SECRETS_PATH"), "POSTGRES_PASSWORD", True)


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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = backend_secrets.get("SECRET_KEY")

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = os.environ.get("DEBUG", "False").capitalize() == "True"

ALLOWED_HOSTS = eval(
    os.environ.get("ALLOWED_HOSTS", '["api.localhost", "localhost", "backend"]')
)


# Application definition

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "djcelery_email",
    "django_prometheus",
    "rest_framework",
    "corsheaders",
    "django_extensions",
    "profile_app",
    "student",
    "volunteer",
]

MIDDLEWARE = []

if not DEBUG:
    MIDDLEWARE += ["django_prometheus.middleware.PrometheusBeforeMiddleware"]
MIDDLEWARE += [
    "django.middleware.security.SecurityMiddleware",
    "whitenoise.middleware.WhiteNoiseMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "corsheaders.middleware.CorsMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
]
if not DEBUG:
    MIDDLEWARE += ["django_prometheus.middleware.PrometheusAfterMiddleware"]

ROOT_URLCONF = "backend.urls"

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [os.path.join(SETTINGS_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",
            ],
        },
    },
]

WSGI_APPLICATION = "backend.wsgi.application"


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

if os.environ.get("POSTGRES_DB"):
    DATABASES = {
        "default": {
            "ENGINE": "django.db.backends.postgresql"
            if DEBUG
            else "django_prometheus.db.backends.postgresql",
            "NAME": os.environ.get("POSTGRES_DB"),
            "USER": os.environ.get("POSTGRES_USER"),
            "PASSWORD": postgres_password,
            "HOST": os.environ.get("POSTGRES_SERVER"),
        }
    }
else:
    DATABASES = {
        "default": {
            "ENGINE": "django.db.backends.sqlite3",
            "NAME": os.path.join(BASE_DIR, "db.sqlite3"),
        }
    }

if os.environ.get("REDIS_URL"):
    # Cache backend
    CACHES = {
        "default": {
            "BACKEND": "django_redis.cache.RedisCache",
            "LOCATION": os.environ.get("REDIS_URL"),
            "OPTIONS": {"CLIENT_CLASS": "django_redis.client.DefaultClient"},
            "KEY_PREFIX": "djangocache",
        }
    }


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

LANGUAGE_CODE = "pt-br"

TIME_ZONE = "America/Sao_Paulo"

USE_I18N = True

USE_L10N = True

USE_TZ = True


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

STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"
WHITENOISE_MAX_AGE = 60 * 60

STATIC_URL = "/static/"

STATIC_ROOT = os.path.join(SETTINGS_DIR, "staticfiles")

AWS_ACCESS_KEY_ID = backend_secrets.get("AWS_ACCESS_KEY_ID")
AWS_SECRET_ACCESS_KEY = backend_secrets.get("AWS_SECRET_ACCESS_KEY")
AWS_STORAGE_BUCKET_NAME = os.environ.get("AWS_STORAGE_BUCKET_NAME")
AWS_DEFAULT_ACL = "public-read"
AWS_AUTO_CREATE_BUCKET = True
AWS_S3_REGION_NAME = "sa-east-1"

if AWS_ACCESS_KEY_ID:
    # S3 Upload
    DEFAULT_FILE_STORAGE = "storages.backends.s3boto3.S3Boto3Storage"
    if not DEBUG:
        # Save static files to S3 in production
        STATICFILES_STORAGE = "storages.backends.s3boto3.S3Boto3Storage"


# Extra places for collectstatic to find static files.
# Uncomment to add backend/static as a static files folder
# STATICFILES_DIRS = (os.path.join(SETTINGS_DIR, "static"),)

# SSL and HTTPS settings
if not DEBUG and eval(os.environ.get("USE_SSL", "False")):
    SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
    SECURE_SSL_REDIRECT = False
    SESSION_COOKIE_SECURE = True
    CSRF_COOKIE_SECURE = True

# Celery
CELERY_BROKER_URL = os.environ.get("CELERY_BROKER_URL")

# Email settings
EMAIL_HOST_USER = os.environ.get("EMAIL_HOST_USER")
EMAIL_HOST_PASSWORD = backend_secrets.get("EMAIL_HOST_PASSWORD")
EMAIL_USE_TLS = json.loads(os.environ.get("EMAIL_USE_TLS", "true").lower())
EMAIL_HOST = os.environ.get("EMAIL_HOST", "smtp.gmail.com")
EMAIL_PORT = int(os.environ.get("EMAIL_PORT", "587"))
DEFAULT_FROM_EMAIL = os.environ.get("DEFAULT_FROM_EMAIL", EMAIL_HOST_USER)
DEFAULT_CONTACT_EMAIL = os.environ.get("DEFAULT_CONTACT_EMAIL", EMAIL_HOST_USER)
SERVER_EMAIL = os.environ.get("SERVER_EMAIL", EMAIL_HOST_USER)
EMAIL_BACKEND = "djcelery_email.backends.CeleryEmailBackend"

ADMINS = [("Admin", os.environ.get("SUPERUSER_EMAIL"))]

# Django Prometheus
PROMETHEUS_EXPORT_MIGRATIONS = False

# Shell plus settings
SHELL_PLUS_PRINT_SQL = True
SHELL_PLUS = "ptipython"
SHELL_PLUS_PRINT_SQL_TRUNCATE = 10000
SHELL_PLUS_SQLPARSE_FORMAT_KWARGS = dict(reindent_aligned=True, truncate_strings=10000)

# Rest Settings
REST_FRAMEWORK = {
    "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.LimitOffsetPagination",
    "DEFAULT_AUTHENTICATION_CLASSES": (
        "backend.authentication.Auth0JWTAuthentication",
        "rest_framework.authentication.SessionAuthentication",
    ),
    "DEFAULT_PERMISSION_CLASSES": ("rest_framework.permissions.IsAuthenticated",),
    "DEFAULT_RENDERER_CLASSES": (
        "djangorestframework_camel_case.render.CamelCaseJSONRenderer",
        "djangorestframework_camel_case.render.CamelCaseBrowsableAPIRenderer",
    ),
    "DEFAULT_PARSER_CLASSES": (
        "djangorestframework_camel_case.parser.CamelCaseFormParser",
        "djangorestframework_camel_case.parser.CamelCaseMultiPartParser",
        "djangorestframework_camel_case.parser.CamelCaseJSONParser",
    ),
}

CORS_ORIGIN_WHITELIST = [os.environ.get("FRONTEND_URL", "http://localhost")]

# Auth0 settings
AUTH0_DOMAIN = social_provider_secrets.get("AUTH0_DOMAIN")
API_IDENTIFIER = social_provider_secrets.get("AUTH0_API_IDENTIFIER")
PUBLIC_KEY = None
JWT_ISSUER = None
JWT_ALGORITHM = "RS256"

if AUTH0_DOMAIN:
    jsonurl = requests.get("https://" + AUTH0_DOMAIN + "/.well-known/jwks.json")
    jwks = jsonurl.json()
    cert = (
        "-----BEGIN CERTIFICATE-----\n"
        + jwks["keys"][0]["x5c"][0]
        + "\n-----END CERTIFICATE-----"
    )
    certificate = load_pem_x509_certificate(cert.encode("utf-8"), default_backend())
    PUBLIC_KEY = certificate.public_key()
    JWT_ISSUER = "https://" + AUTH0_DOMAIN + "/"

SIMPLE_JWT = {
    "ALGORITHM": JWT_ALGORITHM,
    "VERIFYING_KEY": PUBLIC_KEY,
    "AUDIENCE": API_IDENTIFIER,
    "ISSUER": JWT_ISSUER,
    "AUTH_HEADER_TYPES": ("Bearer",),
    "USER_ID_FIELD": "username",
    "USER_ID_CLAIM": "sub",
    "AUTH_TOKEN_CLASSES": ["backend.authentication.NoJWTToken"],
}
