#!/usr/bin/env python

"""
Django settings for core project.
"""

import os
from pathlib import Path
from decouple import Csv,config
from django.utils.translation import gettext_lazy as _


# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.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 = config('SECRET_KEY', default='test', cast=str)

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = config('DEBUG', default=False, cast=bool)

ALLOWED_HOSTS = config('ALLOWED_HOSTS', default='' , cast=Csv())

SITE_ID = config('SITE_ID', default=1, cast=int)

SESSION_COOKIE_SECURE = True
CSRF_COOKIE_HTTPONLY = True
SESSION_COOKIE_AGE = 172800  # 2 days in seconds

# Application definition
INSTALLED_APPS = [
    # Django Apps
    "django.contrib.admin",
    "django.contrib.auth",            # Core authentication framework and its default models.
    "django.contrib.contenttypes",    # Django content type system (allows permissions to be associated with models).
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "django.contrib.sites",
    # Installed Apps
    "ckeditor",
    "storages",
    "mathfilters",
    "import_export",
    "rest_framework",
    "django_countries",
    "django_extensions",
    "django_celery_results",
    # Our Apps
    "apps.root",

    "apps.accounts",
    "apps.profiles",
    "apps.subscriptions",
    "apps.userActivities",

    "apps.process",
    "apps.uploads",

    "apps.newsletter",
    # "apps.shorter",
    "django.contrib.sitemaps",
]

MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",     # Manages sessions across requests
    "django.middleware.common.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",  # Associates users with requests using sessions.
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",

    "apps.accounts.middleware.OneSessionPerUserMiddleware",
    "apps.userActivities.middleware.UserActivityMiddleware",
    "apps.accounts.middleware.ReferrerPolicyMiddleware"
    
    # "social_django.middleware.SocialAuthExceptionMiddleware",   # Manages social_django
]

ROOT_URLCONF = "core.urls"

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",
                "apps.subscriptions.context.plans_context.get_plans",
                "apps.subscriptions.context.plans_context.monthly_plans",
                "apps.subscriptions.context.plans_context.paypal_info"
            ],
            "builtins": [
                "apps.process.templatetags.has_youtube",
                "apps.process.templatetags.has_youtube_upload",
                "apps.subscriptions.templatetags.valid_extension",
                "apps.subscriptions.templatetags.reached_upload_limit",
                "apps.subscriptions.templatetags.total_videos",
                "apps.subscriptions.templatetags.videos_per_day",
                "apps.subscriptions.templatetags.rest_videos",
            ]
        },
    },
]

WSGI_APPLICATION = "core.wsgi.application"


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

DATABASES = {
    "default": {
        "ENGINE"   : config('SQL_ENGINE', default='django.db.backends.sqlite3', cast=str),
        "NAME"     : config('SQL_DATABASE', default=(BASE_DIR/'db.sqlite3'), cast=str),
        "USER"     : config('SQL_USER', default='user', cast=str),
        "PASSWORD" : config('SQL_PASSWORD', default='password', cast=str),
        "HOST"     : config('SQL_HOST', default='localhost', cast=str),
        "PORT"     : config('SQL_PORT', default='5432', cast=int),
    },
}


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

# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/

LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'

USE_I18N = True
USE_L10N = True
USE_TZ = True

LANGUAGE_CODE = 'en'
LANGUAGES = [
    ('ar', _('Arabic')),
    ('en', _('English')),
    ('fr', _('French')),
]

LOCALE_PATHS = (
    (BASE_DIR/'locale'),
)


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

# STATIC_URL       = "/static/"
# STATIC_ROOT      = (BASE_DIR/"staticfiles")
# STATICFILES_DIRS = [(BASE_DIR/"static"),]

# MEDIA_URL        = "/media/"
# MEDIA_ROOT       = (BASE_DIR/"media")

# Django storage settings
STATICFILES_DIRS = [
    (BASE_DIR/'static'),
]

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

DEFAULT_AUTO_FIELD      = 'django.db.models.BigAutoField'

# Custom Account (User)
AUTH_USER_MODEL         = 'accounts.User'

# Load an integer setting
MAX_UPLOAD_SIZE         = config('MAX_UPLOAD_SIZE', default=1024, cast=int)

AWS_DEFAULT_REGION_NAME = config('AWS_DEFAULT_REGION_NAME', default='us-east-1', cast=str)
# AWS S3 settings
AWS_ACCESS_KEY_ID       = config('AWS_ACCESS_KEY_ID', default='', cast=str)
AWS_SECRET_ACCESS_KEY   = config('AWS_SECRET_ACCESS_KEY', default='', cast=str)
AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET_NAME', default='', cast=str)
AWS_S3_REGION_NAME      = config('AWS_S3_REGION_NAME', default=AWS_DEFAULT_REGION_NAME, cast=str)
AWS_DEFAULT_ACL         = None

AWS_LOCATION            = 'static/'
AWS_S3_URL_PROTOCOL     = 'https:'

STATICFILES_STORAGE      = 'core.storage_backends.StaticStorage'
DEFAULT_FILE_STORAGE     = 'core.storage_backends.MediaStorage'

# AWS_S3_CUSTOM_DOMAIN    = f'{AWS_STORAGE_BUCKET_NAME}.s3.{AWS_S3_REGION_NAME}.amazonaws.com'
AWS_S3_CUSTOM_DOMAIN     = 'd3i6wd5yhzcp9n.cloudfront.net'
AWS_S3_OBJECT_PARAMETERS = {
    'CacheControl': 'max-age=86400',
}

STATIC_URL              = f'{AWS_S3_URL_PROTOCOL}//{AWS_S3_CUSTOM_DOMAIN}/{AWS_LOCATION}'
MEDIA_URL               = f'{AWS_S3_URL_PROTOCOL}//{AWS_S3_CUSTOM_DOMAIN}/media/'


# Email SETTING
EMAIL_BACKEND           = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST              = config('EMAIL_HOST', default='smtp.gmail.com', cast=str)
EMAIL_PORT              = config('EMAIL_PORT', default=587, cast=int)
EMAIL_USE_TLS           = config('EMAIL_USE_TLS', default=True, cast=bool)
EMAIL_HOST_USER         = config('EMAIL_HOST_USER', default='', cast=str)
EMAIL_HOST_PASSWORD     = config('EMAIL_HOST_PASSWORD', default='', cast=str)
DEFAULT_FROM_EMAIL      = EMAIL_HOST_USER

#
SESSION_COOKIE_AGE      = 60 * 60 * 24 * 2
TOKEN_EXPIRY_SECONDS    = 60 * 60 * 6

# Google API SETTING
CLIENT_ID               = config("CLIENT_ID", default="", cast=str)
CLIENT_SECRET           = config("CLIENT_SECRET", default="", cast=str)
REDIRECT_URI            = config("REDIRECT_URI", default="", cast=str)

os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"

CLIENT_SECRETS_FILE     = "json_credentials.json"
JSON_PATH               = os.path.join(os.getcwd(), "data", CLIENT_SECRETS_FILE)
SCOPES                  = ["https://www.googleapis.com/auth/youtube.upload"]
API_SERVICE_NAME        = "youtube"
API_VERSION             = "v3"

# Paypal API SETTING
PAYPAL_CLIENTID         = config("PAYPAL_CLIENTID", default="", cast=str)
PAYPAL_SECRETID         = config("PAYPAL_SECRETID", default="", cast=str)

# Celery Configuration Options
CELERY_ACCEPT_CONTENT           = ['application/json']
CELERY_RESULT_SERIALIZER        = 'json'
CELERY_TASK_SERIALIZER          = 'json'
CELERY_TASK_DEFAULT_QUEUE       = 'default'
CELERY_BROKER_URL               = f"sqs://{AWS_ACCESS_KEY_ID}:{AWS_SECRET_ACCESS_KEY}@"
CELERY_BROKER_TRANSPORT_OPTIONS = {
    "region": config('AWS_SQS_REGION_NAME', default=AWS_DEFAULT_REGION_NAME, cast=str),
    'queue_name_prefix': 'django-',
    'visibility_timeout': 7200,
    'polling_interval': 1
}
# Using the database to store task state and results.
CELERY_RESULT_BACKEND           = 'django-db' # None
CELERY_TASK_ANNOTATIONS         = {'*': {'default_retry_delay': 5, 'max_retries': 12}}
TASK_ACKS_LATE                  = True
WORKER_PREFETCH_MULTIPLIER      = 1

# CELERY_BEAT_SCHEDULE = {
#     'job_timeout_checker': {
#         'task': 'job_timeout_checker',
#         'schedule': timedelta(seconds=60),
#     },
# }

AUTHENTICATION_BACKENDS = [
    'apps.accounts.backends.NonePasswordBackend',
    'django.contrib.auth.backends.ModelBackend',
    # Add other authentication backends if needed
]

MAILER_LITE_KEY                 = config("MAILER_LITE_KEY", default="", cast=str)
SECURE_CROSS_ORIGIN_OPENER_POLICY = 'same-origin-allow-popups'  

MAILER_LITE_GROUPS = {
    'Pro_Weekly': 93482043876312205,
    'Creator_Weekly': 93482004214973973,
    'Basic_Weekly': 93481969647617643,

    'Premium_Monthly': 93482050733999790,
    'Creator_Monthly': 93482022784206296,
    'Basic_Monthly': 93481978982040806,

    'Premium_Yearly': 93482056788477144,    
    'Creator_Yearly': 93482029223511726,
    'Basic_Yearly': 93481992532789065,
    
    'Newsletter': 93482072370317085,
    'Free_Plan': 93481471525783371,
    'Upgrade_Group': 94299370182149429,

    'Welcome_Group': 96750764932728508,

    'Forgot_Pass': 97219476934624610,
    'Contact_Us': 97219484146730691
}
 
