"""
Django settings for base project.

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

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

For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.2/ref/settings/
"""
import os
from decouple import config

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = config('SECRET_KEY')

DEBUG = False
DEBUG_CACHING = False

# SESSION_COOKIE_SECURE = False
# CSRF_COOKIE_SECURE = False
# SECURE_SSL_REDIRECT = False
# SECURE_SSL_HOST = False

CSP_FONT_SRC = ("'self'", "https://fonts.gstatic.com")
CSP_STYLE_SRC = ("'self'", "https://fonts.googleapis.com")

LOGOUT_REDIRECT_URL = "/"

INSTALLED_APPS = [
    "base", 
    'django_extensions',
    
    # Libraries
    'widget_tweaks',
    'captcha',
    'corsheaders',
    "compressor",
    'htmlmin',
    'cachalot',

    # Django Deafults
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    "django.contrib.sites",
    
    # Base Apps
    'admin_base',
    'website',
]

if DEBUG:
    INSTALLED_APPS.insert(0, 'debug_toolbar')
    INSTALLED_APPS.insert(-1, 'django_browser_reload')

MIDDLEWARE_REST = [    
    # Security Middleware
    'django.middleware.security.SecurityMiddleware',

    # WhiteNoise Middleware for static files
    "whitenoise.middleware.WhiteNoiseMiddleware",
    
    # Session Management
    'django.contrib.sessions.middleware.SessionMiddleware',
    
    #Language Managment Middleware
    'django.middleware.locale.LocaleMiddleware',

    # CORS Middleware
    'corsheaders.middleware.CorsMiddleware',

    # Authentication and CSRF
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    
    # Messaging and Clickjacking Protection
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',

    # Static File Compression
    'django.middleware.gzip.GZipMiddleware',

    # HTML Minification Middleware
    #'htmlmin.middleware.HtmlMinifyMiddleware',
    
    'django.middleware.cache.FetchFromCacheMiddleware',
    #'htmlmin.middleware.MarkRequestMiddleware',
    
    "admin_base.middleware.URLLanguageConfigMiddleware",
]

if DEBUG:
    # Browser reload (development only)
    MIDDLEWARE_REST.insert(-2, "django_browser_reload.middleware.BrowserReloadMiddleware",)
    # Additional middleware (Debug, etc.)
    MIDDLEWARE_REST.insert(-3, "debug_toolbar.middleware.DebugToolbarMiddleware",)

# ORDER MATTERS WEHEYAT, ana ba2aly 19 days fe issue el caching we el halha el order. Shokran bas a7a
if DEBUG == True and DEBUG_CACHING == False:
    MIDDLEWARE = [
        # Cache Disabled
        'django.middleware.common.CommonMiddleware',
        "admin_base.middleware.TrailingSlashMiddleware",
    ] + MIDDLEWARE_REST

else:
    MIDDLEWARE = [
        # Cache enabled
        "admin_base.middleware.CacheUpdateMiddleware",
        'django.middleware.common.CommonMiddleware',
        'django.middleware.cache.UpdateCacheMiddleware',
        "admin_base.middleware.TrailingSlashMiddleware",
    ] + MIDDLEWARE_REST

ROOT_URLCONF = 'base.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': False,
        'OPTIONS': {
            
            'loaders': [
                ('django.template.loaders.cached.Loader', [
                    'django.template.loaders.filesystem.Loader',
                    'django.template.loaders.app_directories.Loader',
                ]),
            ],
            
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'admin_base.context_processors.base_context',
                'cms.context_processors.general'
            ],
            
            'loaders':[(
               'django.template.loaders.cached.Loader', [
                  'django.template.loaders.filesystem.Loader',
                  'django.template.loaders.app_directories.Loader',
               ]
            )],
             
        },
    },
]

WSGI_APPLICATION = 'base.wsgi.application'


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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': "db.sqlite3",
    },
}


# Password validation
# https://docs.djangoproject.com/en/4.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/4.2/topics/i18n/
USE_I18N = True
USE_L10N = True

TIME_ZONE = 'UTC'

USE_TZ = True

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

# Define the base static URL path
STATIC_URL = '/static/'

# Static files directories (same for both development and production)
STATICFILES_DIRS = [
    
    ]

# Separate directory to collect static files for production
STATIC_ROOT = os.path.join(BASE_DIR, 'production_static')

# Media files configuration
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

# Whitenoise storage for static files (compression, no caching)
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage'
#STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'


# Staticfiles finders
STATICFILES_FINDERS = [
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',

    'compressor.finders.CompressorFinder',
]

# Django Compressor & Libsass configuration
# COMPRESS_ENABLED = DEBUG
COMPRESS_ENABLED = False

COMPRESS_PRECOMPILERS = (
    ('text/x-scss', 'django_libsass.SassCompiler'),
)

# LIBSASS_ARGUMENTS = {
#     'style': 'compressed',  # or 'nested' depending on your preference
#     'precision': 8,
#     '--poll': True,  # Poll the filesystem for changes
# }

# HTML Minifier Configuration
EXCLUDE_FROM_MINIFYING = ('admin/','admin/*')
HTML_MINIFY = not DEBUG
KEEP_COMMENTS_ON_MINIFYING = not DEBUG

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

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

# Log Configration
LOGGING = {
    'version': 1,
    
    'disable_existing_loggers': True,
    
    'formatters': {
        'verbose': {
            'format': '{levelname} {asctime} {module} {message}',
            'style': '{',
        },
        
        'simple': {
            'format': '{levelname} {module} {message}',
            'style': '{',
        },
    },
    
    'handlers': {
        'django_file': {
            'level': 'INFO',
            'class': 'logging.FileHandler',
            'filename': 'log/django.log',
            'formatter': 'verbose',
        },
        
        'custom_file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': 'log/debug.log',
            'formatter': 'simple',
        },
        
        'console': {
            'level': 'INFO',
            'class': 'logging.StreamHandler',
            'formatter': 'simple'
        },
    },
    
    'loggers': {
        'django': {
            'handlers': ['django_file'],
            'level': 'INFO',
            'propagate': False,
        },
        
        'debug_logger': {
            'handlers': ['custom_file'],
            'level': 'DEBUG',
            'propagate': False,
        },
    },
}

if DEBUG:
    # Replace all logger handlers with console handler in DEBUG mode.
    for logger_name in LOGGING['loggers']:
        LOGGING['loggers'][logger_name]['handlers'] = ['console']

LOGIN_URL = '/admin/login/'

# Caching System
# CACHES = {
#     'default': {
#         'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
#         'LOCATION': BASE_DIR + '/cache',
#     }
# }

# CACHES = {
#     'default': {
#         'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',  # For in-memory cache
#         'LOCATION': 'unique-snowflake',
#     }
# }

# Cache settings
CACHE_MIDDLEWARE_SECONDS = 60 * 60 * 24 * 30  # 30 days

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
        'LOCATION': BASE_DIR + '/cache',
        'TIMEOUT': CACHE_MIDDLEWARE_SECONDS,
    }
}

# IP settings
if DEBUG:
    BASE_URL = '127.0.0.1:8000'
    
    ALLOWED_HOSTS = ["*"]

    CORS_ALLOWED_ORIGINS = [
        "http://127.0.0.1:8000",
        "http://example.com",
    ]

    INTERNAL_IPS = [
        '127.0.0.1',  # Localhost
        "*"
    ]
    

WHITENOISE_KEEP_ONLY_HASHED_FILES = True

#########################################################################################################################################################

################# General Configuration #################

if not DEBUG:
    BASE_URL = 'example.com'
    
    ALLOWED_HOSTS = ["*"]

    CORS_ALLOWED_ORIGINS = [
        "http://127.0.0.1:8000",
        "https://example.com",
    ]

    INTERNAL_IPS = [
        '127.0.0.1',  # Localhost
    ]

################# Cache Configuration Settings #################
CACHE_MIDDLEWARE_ALIAS = 'default'
CACHE_MIDDLEWARE_SECONDS = 60 * 60 * 24 * 30
CACHE_MIDDLEWARE_KEY_PREFIX = ''

# Email Configuration Settings
# EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
# EMAIL_HOST = config("EMAIL_HOST")
# EMAIL_PORT = 465
# EMAIL_USE_TLS = False
# EMAIL_USE_SSL = True
# EMAIL_HOST_USER = config("EMAIL_HOST_USER")
# EMAIL_HOST_PASSWORD = config("EMAIL_HOST_PASSWORD")

################# Website App Configuration Settings #################
STATICFILES_DIRS += os.path.join(BASE_DIR, 'website', 'static'),

LANGUAGES = [
    ('en', 'English'),
    ('ar', 'Arabic'),
]

LANGUAGE_CODE = 'en'
DEFAULT_LANGUAGE = LANGUAGE_CODE

if DEBUG:
    WEBSITE_MEDIA_ROOT = os.path.join(BASE_DIR, 'website/static/website/img')
    
elif not DEBUG:
    WEBSITE_MEDIA_ROOT = os.path.join(BASE_DIR, 'production_static/website/img')

################# CMS App Configuration Settings #################
INSTALLED_APPS += ['cms']
STATICFILES_DIRS += [
    os.path.join(BASE_DIR, 'cms/static'),
]
if DEBUG:
    CMS_MEDIA_ROOT = os.path.join(BASE_DIR, 'cms/static/cms/img')
    
elif not DEBUG:
    CMS_MEDIA_ROOT = os.path.join(BASE_DIR, 'production_static/cms/img')

STATICFILES_DIRS += [os.path.join(BASE_DIR, "cms/static"),]

################# SEO App Configuration Settings #################
INSTALLED_APPS += ["seo", "robots", 'django.contrib.sitemaps',]
SITE_ID = 1