"""
Django settings for project project.

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

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

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

from django.core.management.utils import get_random_secret_key

from datetime import timedelta
from dotenv import load_dotenv
from pathlib import Path

import sys
import os

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

load_dotenv()

if os.getenv("BACKEND_DEBUG_MODE") is not None:
    if os.getenv("BACKEND_DEBUG_MODE").lower() == 'true':
        DEBUG = True
    else:
        DEBUG = False
else:
    print("'BACKEND_DEBUG_MODE' env variable is not defined, setting up 'BACKEND_DEBUG_MODE' as 'False'")
    DEBUG = False
print(f'DEBUG:\t\t', DEBUG)

if (SECRET_KEY := os.getenv("BACKEND_SECRET_KEY")) is not None:
    pass
else:
    print("'BACKEND_SECRET_KEY' env variable is not defined, setting up random 'BACKEND_SECRET_KEY'")
    SECRET_KEY = get_random_secret_key()
if DEBUG:
    print('SECRET KEY:\t', SECRET_KEY)

if (ALLOWED_HOSTS := os.getenv("BACKEND_ALLOWED_HOSTS")) is not None:
    ALLOWED_HOSTS = ALLOWED_HOSTS.split(' ')
    print('ALLOWED HOSTS:\t', ALLOWED_HOSTS)
else:
    print("'BACKEND_ALLOWED_HOSTS' env variable is not defined, setting up 'BACKEND_ALLOWED_HOSTS' as empty list: []")
    ALLOWED_HOSTS = []

# Application definition

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

    'rest_framework.authtoken',
    'rest_framework',
    'corsheaders',
    'djoser',
    'drf_yasg',

    'storages',
    'main_app',
]

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',
    'django.middleware.locale.LocaleMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
]

ROOT_URLCONF = 'project.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        '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 = 'project.wsgi.application'

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


if (BACKEND_DEFAULT_DB := os.getenv("BACKEND_DEFAULT_DB")) is not None:
    print('DEFAULT_DB:\t', BACKEND_DEFAULT_DB)
else:
    print("'BACKEND_DEFAULT_DB' env variable is not defined, setting up 'BACKEND_DEFAULT_DB' as 'PostgreSQL'")
    BACKEND_DEFAULT_DB = 'PostgreSQL'

if BACKEND_DEFAULT_DB == 'PostgreSQL' or BACKEND_DEFAULT_DB == 'SQLite':
    DEFAULT_DATABASE = BACKEND_DEFAULT_DB
else:
    print("'BACKEND_DEFAULT_DB' env has wrong value, setting up 'BACKEND_DEFAULT_DB' as 'PostgreSQL'")
    DEFAULT_DATABASE = 'PostgreSQL'

if DEFAULT_DATABASE == 'SQLite':
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': BASE_DIR / 'db.sqlite3',
        }
    }
elif DEFAULT_DATABASE == 'PostgreSQL':
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.postgresql',
            'NAME': os.environ.get('DB_NAME'),
            'USER': os.environ.get('DB_USER'),
            'PASSWORD': os.environ.get('DB_PASSWORD'),
            'HOST': os.environ.get('DB_HOST'),
            'PORT': 5432,
        }
    }
else:
    print('ERROR: Database is not defined ! ! !')
    sys.exit()

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

LANGUAGE_CODE = 'ru-RU'

TIME_ZONE = 'Europe/Moscow'

USE_I18N = True

USE_L10N = True

USE_TZ = True

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

STATIC_URL = '/static_django/'
STATIC_ROOT = os.path.join(os.path.abspath(os.curdir), 'static_django')

MEDIA_ROOT = str(BASE_DIR) + '/media/'
MEDIA_URL = '/media/'

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

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

CORS_ORIGIN_ALLOW_ALL = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ),
    # 'DEFAULT_PERMISSION_CLASSES': [
    #     'rest_framework.permissions.IsAuthenticated',
    # ]
}

SIMPLE_JWT = {
    'ACCESS_TOKEN_LIFETIME': timedelta(days=1),
    'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
    'AUTH_HEADER_TYPES': ('Bearer',),
}

DJOSER = {
    'PASSWORD_RESET_SHOW_EMAIL_NOT_FOUND': True,
    'PASSWORD_RESET_CONFIRM_URL': 'password/reset/confirm/?uid={uid}&token={token}',
    'USERNAME_RESET_CONFIRM_URL': '#/username/reset/confirm/{uid}/{token}',
    'ACTIVATION_URL': 'activate/?uid={uid}&token={token}',
    'SEND_ACTIVATION_EMAIL': False,
    'SERIALIZERS': {},
    'SET_PASSWORD_RETYPE': True,
}

# S3 Storage

if os.getenv("BACKEND_DEFAULT_STORAGE") is not None:
    DEFAULT_STORAGE = os.getenv("BACKEND_DEFAULT_STORAGE")
else:
    print("'BACKEND_DEFAULT_STORAGE' env variable is not defined, setting up 'BACKEND_DEFAULT_STORAGE' as 'FILE_SYSTEM'")
    DEFAULT_STORAGE = 'FILE_SYSTEM'

if DEFAULT_STORAGE == 'FILE_SYSTEM':
    print(f'DEFAULT_STORAGE:\t', DEFAULT_STORAGE)
    pass
elif DEFAULT_STORAGE == 'S3':
    DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
    STATICFILES_STORAGE = 'storages.backends.s3boto3.S3StaticStorage'

    if (AWS_S3_ENDPOINT_URL := os.getenv("BACKEND_AWS_S3_ENDPOINT_URL")) is None:
        print("'BACKEND_AWS_S3_ENDPOINT_URL' env variable is not defined")
        sys.exit()

    if (AWS_ACCESS_KEY_ID := os.getenv("BACKEND_AWS_ACCESS_KEY_ID")) is None:
        print("'BACKEND_AWS_ACCESS_KEY_ID' env variable is not defined")
        sys.exit()

    if (AWS_SECRET_ACCESS_KEY := os.getenv("BACKEND_AWS_SECRET_ACCESS_KEY")) is None:
        print("'BACKEND_AWS_SECRET_ACCESS_KEY' env variable is not defined")
        sys.exit()

    if (AWS_STORAGE_BUCKET_NAME := os.getenv("BACKEND_AWS_STORAGE_BUCKET_NAME")) is None:
        print("'BACKEND_AWS_STORAGE_BUCKET_NAME' env variable is not defined")
        sys.exit()

    if (AWS_S3_REGION_NAME := os.getenv("BACKEND_AWS_S3_REGION_NAME")) is None:
        print("'BACKEND_AWS_S3_REGION_NAME' env variable is not defined")
        sys.exit()

    AWS_DEFAULT_ACL = "public-read"

    if DEBUG:
        print('AWS_S3_ENDPOINT_URL:\t', AWS_S3_ENDPOINT_URL)
        print('AWS_ACCESS_KEY_ID:\t', AWS_ACCESS_KEY_ID)
        print('AWS_SECRET_ACCESS_KEY:\t', AWS_SECRET_ACCESS_KEY)
        print('AWS_STORAGE_BUCKET_NAME:\t', AWS_STORAGE_BUCKET_NAME)
        print('AWS_S3_REGION_NAME:\t', AWS_S3_REGION_NAME)

    print(f'DEFAULT_STORAGE:\t', DEFAULT_STORAGE)

    # AWS_S3_BUCKET_NAME_STATIC = os.environ.get('AWS_S3_BUCKET_NAME_STATIC')
    # AWS_S3_ADDRESSING_STYLE='path'
else:
    print(
        f"'BACKEND_DEFAULT_STORAGE' env has wrong value: {DEFAULT_STORAGE}, setting up 'BACKEND_DEFAULT_STORAGE' as 'HOST'")

"""
Django settings for project project.

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

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

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

from django.core.management.utils import get_random_secret_key

from datetime import timedelta
from dotenv import load_dotenv
from pathlib import Path

import sys
import os

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

load_dotenv()

if os.getenv("BACKEND_DEBUG_MODE") is not None:
    if os.getenv("BACKEND_DEBUG_MODE").lower() == 'true':
        DEBUG = True
    else:
        DEBUG = False
else:
    print("'BACKEND_DEBUG_MODE' env variable is not defined, setting up 'BACKEND_DEBUG_MODE' as 'False'")
    DEBUG = False
print(f'DEBUG:\t\t', DEBUG)

if (SECRET_KEY := os.getenv("BACKEND_SECRET_KEY")) is not None:
    pass
else:
    print("'BACKEND_SECRET_KEY' env variable is not defined, setting up random 'BACKEND_SECRET_KEY'")
    SECRET_KEY = get_random_secret_key()
if DEBUG:
    print('SECRET KEY:\t', SECRET_KEY)

if (ALLOWED_HOSTS := os.getenv("BACKEND_ALLOWED_HOSTS")) is not None:
    ALLOWED_HOSTS = ALLOWED_HOSTS.split(' ')
    print('ALLOWED HOSTS:\t', ALLOWED_HOSTS)
else:
    print("'BACKEND_ALLOWED_HOSTS' env variable is not defined, setting up 'BACKEND_ALLOWED_HOSTS' as empty list: []")
    ALLOWED_HOSTS = []

# Application definition

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

    'rest_framework.authtoken',
    'rest_framework',
    'corsheaders',
    'djoser',
    'drf_yasg',

    'storages',
    'main_app',
]

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',
    'django.middleware.locale.LocaleMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
]

ROOT_URLCONF = 'project.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        '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 = 'project.wsgi.application'

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


if (BACKEND_DEFAULT_DB := os.getenv("BACKEND_DEFAULT_DB")) is not None:
    print('DEFAULT_DB:\t', BACKEND_DEFAULT_DB)
else:
    print("'BACKEND_DEFAULT_DB' env variable is not defined, setting up 'BACKEND_DEFAULT_DB' as 'PostgreSQL'")
    BACKEND_DEFAULT_DB = 'PostgreSQL'

if BACKEND_DEFAULT_DB == 'PostgreSQL' or BACKEND_DEFAULT_DB == 'SQLite':
    DEFAULT_DATABASE = BACKEND_DEFAULT_DB
else:
    print("'BACKEND_DEFAULT_DB' env has wrong value, setting up 'BACKEND_DEFAULT_DB' as 'PostgreSQL'")
    DEFAULT_DATABASE = 'PostgreSQL'

if DEFAULT_DATABASE == 'SQLite':
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': BASE_DIR / 'db.sqlite3',
        }
    }
elif DEFAULT_DATABASE == 'PostgreSQL':
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.postgresql',
            'NAME': os.environ.get('DB_NAME'),
            'USER': os.environ.get('DB_USER'),
            'PASSWORD': os.environ.get('DB_PASSWORD'),
            'HOST': os.environ.get('DB_HOST'),
            'PORT': 5432,
        }
    }
else:
    print('ERROR: Database is not defined ! ! !')
    sys.exit()

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

LANGUAGE_CODE = 'ru-RU'

TIME_ZONE = 'Europe/Moscow'

USE_I18N = True

USE_L10N = True

USE_TZ = True

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

STATIC_URL = '/static_django/'
STATIC_ROOT = os.path.join(os.path.abspath(os.curdir), 'static_django')

MEDIA_ROOT = str(BASE_DIR) + '/media/'
MEDIA_URL = '/media/'

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

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

CORS_ORIGIN_ALLOW_ALL = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ),
    # 'DEFAULT_PERMISSION_CLASSES': [
    #     'rest_framework.permissions.IsAuthenticated',
    # ]
}

SIMPLE_JWT = {
    'ACCESS_TOKEN_LIFETIME': timedelta(days=1),
    'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
    'AUTH_HEADER_TYPES': ('Bearer',),
}

DJOSER = {
    'PASSWORD_RESET_SHOW_EMAIL_NOT_FOUND': True,
    'PASSWORD_RESET_CONFIRM_URL': 'password/reset/confirm/?uid={uid}&token={token}',
    'USERNAME_RESET_CONFIRM_URL': '#/username/reset/confirm/{uid}/{token}',
    'ACTIVATION_URL': 'activate/?uid={uid}&token={token}',
    'SEND_ACTIVATION_EMAIL': False,
    'SERIALIZERS': {},
    'SET_PASSWORD_RETYPE': True,
}

# S3 Storage

if os.getenv("BACKEND_DEFAULT_STORAGE") is not None:
    DEFAULT_STORAGE = os.getenv("BACKEND_DEFAULT_STORAGE")
else:
    print("'BACKEND_DEFAULT_STORAGE' env variable is not defined, setting up 'BACKEND_DEFAULT_STORAGE' as 'FILE_SYSTEM'")
    DEFAULT_STORAGE = 'FILE_SYSTEM'

if DEFAULT_STORAGE == 'FILE_SYSTEM':
    print(f'DEFAULT_STORAGE:\t', DEFAULT_STORAGE)
    pass
elif DEFAULT_STORAGE == 'S3':
    DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
    STATICFILES_STORAGE = 'storages.backends.s3boto3.S3StaticStorage'

    if (AWS_S3_ENDPOINT_URL := os.getenv("BACKEND_AWS_S3_ENDPOINT_URL")) is None:
        print("'BACKEND_AWS_S3_ENDPOINT_URL' env variable is not defined")
        sys.exit()

    if (AWS_ACCESS_KEY_ID := os.getenv("BACKEND_AWS_ACCESS_KEY_ID")) is None:
        print("'BACKEND_AWS_ACCESS_KEY_ID' env variable is not defined")
        sys.exit()

    if (AWS_SECRET_ACCESS_KEY := os.getenv("BACKEND_AWS_SECRET_ACCESS_KEY")) is None:
        print("'BACKEND_AWS_SECRET_ACCESS_KEY' env variable is not defined")
        sys.exit()

    if (AWS_STORAGE_BUCKET_NAME := os.getenv("BACKEND_AWS_STORAGE_BUCKET_NAME")) is None:
        print("'BACKEND_AWS_STORAGE_BUCKET_NAME' env variable is not defined")
        sys.exit()

    if (AWS_S3_REGION_NAME := os.getenv("BACKEND_AWS_S3_REGION_NAME")) is None:
        print("'BACKEND_AWS_S3_REGION_NAME' env variable is not defined")
        sys.exit()

    AWS_DEFAULT_ACL = "public-read"

    if DEBUG:
        print('AWS_S3_ENDPOINT_URL:\t', AWS_S3_ENDPOINT_URL)
        print('AWS_ACCESS_KEY_ID:\t', AWS_ACCESS_KEY_ID)
        print('AWS_SECRET_ACCESS_KEY:\t', AWS_SECRET_ACCESS_KEY)
        print('AWS_STORAGE_BUCKET_NAME:\t', AWS_STORAGE_BUCKET_NAME)
        print('AWS_S3_REGION_NAME:\t', AWS_S3_REGION_NAME)

    print(f'DEFAULT_STORAGE:\t', DEFAULT_STORAGE)

    # AWS_S3_BUCKET_NAME_STATIC = os.environ.get('AWS_S3_BUCKET_NAME_STATIC')
    # AWS_S3_ADDRESSING_STYLE='path'
else:
    print(
        f"'BACKEND_DEFAULT_STORAGE' env has wrong value: {DEFAULT_STORAGE}, setting up 'BACKEND_DEFAULT_STORAGE' as 'HOST'")

Django settings for project project.  Generated by 'django-admin startproject' using Django 3.2.  For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/  For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ # Build paths inside the project like this: BASE_DIR / 'subdir'. # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # Application definition # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases # Password validation # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators # Internationalization # https://docs.djangoproject.com/en/3.2/topics/i18n/ # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.2/howto/static-files/ # Default primary key field type # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field # 'DEFAULT_PERMISSION_CLASSES': [ #     'rest_framework.permissions.IsAuthenticated', # ] # S3 Storage # AWS_S3_BUCKET_NAME_STATIC = os.environ.get('AWS_S3_BUCKET_NAME_STATIC') # AWS_S3_ADDRESSING_STYLE='path'