"""
Django settings for N3wtSchool project.

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

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

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

from pathlib import Path
import json
import os
from datetime import timedelta
import logging

# Configuration du logger
logger = logging.getLogger(__name__)

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
MEDIA_URL = '/data/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'data')

BASE_URL = os.getenv('BASE_URL', 'http://localhost:3000')


LOGIN_REDIRECT_URL = '/Subscriptions/registerForms'

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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-afjm6kvigncxzx6jjjf(qb0n(*qvi#je79r=gqflcn007d_ve9'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['*']

# Application definition

INSTALLED_APPS = [
    'Common.apps.CommonConfig',
    'Subscriptions.apps.GestioninscriptionsConfig',
    'Auth.apps.GestionloginConfig',
    'GestionMessagerie.apps.GestionMessagerieConfig',
    'GestionEmail.apps.GestionEmailConfig',
    'GestionNotification.apps.GestionNotificationConfig',
    'School.apps.SchoolConfig',
    'Planning.apps.PlanningConfig',
    'Establishment.apps.EstablishmentConfig',
    'Settings.apps.SettingsConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'corsheaders',
    'django_celery_beat',
    'N3wtSchool',
    'drf_yasg',
    'rest_framework_simplejwt',
    'channels',
]

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    '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',
    'N3wtSchool.middleware.ContentSecurityPolicyMiddleware'
]


ROOT_URLCONF = 'N3wtSchool.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / "templates", BASE_DIR / "static/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',
            ],
        },
    },
]

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.redis.RedisCache',
        'LOCATION': 'redis://redis:6379',
    }
}
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
SESSION_CACHE_ALIAS = 'default'

WSGI_APPLICATION = 'N3wtSchool.wsgi.application'


#LOGGING
LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
      "formatters": {  # Ajout des formateurs
        "verbose": {
            "format": "{asctime} [{levelname}] [{name}] {module}.{funcName} - {message}",
            "style": "{",
            "datefmt": "%Y-%m-%d %H:%M:%S"
        }
    },
    "handlers": {
        "console": {
            "class": "logging.StreamHandler",
            "formatter": "verbose",  # Utilisation du formateur
        },
    },
    "root": {
        "handlers": ["console"],
        "level": os.getenv("ROOT_LOG_LEVEL", "INFO"),
    },
    "loggers": {

        "celery": {
            "handlers": ["console"],
            "level": os.getenv("CELERY_LOG_LEVEL", "INFO"),
            "propagate": False,
        },
        "N3wtSchool": {
            "handlers": ["console"],
            "level": os.getenv("N3WTSCHOOL_LOG_LEVEL", "INFO"),
            "propagate": False,
        },
        "GestionNotification": {
            "handlers": ["console"],
            "level": os.getenv("GESTION_NOTIFICATION_LOG_LEVEL", "INFO"),
            "propagate": False,
        },
        "Auth": {
            "handlers": ["console"],
            "level": os.getenv("GESTION_LOGIN_LOG_LEVEL", "INFO"),
            "propagate": False,
        },
        "Subscriptions": {
            "handlers": ["console"],
            "level": os.getenv("GESTION_INSCRIPTIONS_LOG_LEVEL", "DEBUG"),
            "propagate": False,
        },
        "GestionMessagerie": {
            "handlers": ["console"],
            "level": os.getenv("GESTION_MESSAGERIE_LOG_LEVEL", "INFO"),
            "propagate": False,
        },
        "GestionEmail": {
            "handlers": ["console"],
            "level": os.getenv("GESTION_EMAIL_LOG_LEVEL", "INFO"),
            "propagate": False,
        },
        "School": {
            "handlers": ["console"],
            "level": os.getenv("GESTION_ENSEIGNANTS_LOG_LEVEL", "INFO"),
            "propagate": False,
        },
    },
}

# Password validation
# https://docs.djangoproject.com/en/5.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
        'OPTIONS': {
            'min_length': 6,
        }
    },
    #{
    #    'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    #},
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


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

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True


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

DEBUG = True

STATIC_URL = 'static/'

STATICFILES_DIRS = [
    BASE_DIR / 'static',
]

STATIC_ROOT = BASE_DIR / 'staticfiles'


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

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

########################################################################
#################### Application Settings ##############################
########################################################################



DJANGO_SUPERUSER_PASSWORD='admin'
DJANGO_SUPERUSER_USERNAME='admin'
DJANGO_SUPERUSER_EMAIL='admin@n3wtschool.com'
# Configuration de l'email de l'application
smtp_config_file = 'N3wtSchool/Configuration/application.json'

if os.path.exists(smtp_config_file):
    try:
        with open(smtp_config_file, 'r') as f:
            smtpSettings = json.load(f)
        EMAIL_HOST = smtpSettings.get('hostSMTP', '')
        EMAIL_PORT = smtpSettings.get('portSMTP', 587)
        EMAIL_HOST_USER = smtpSettings.get('username', '')
        EMAIL_HOST_PASSWORD = smtpSettings.get('password', '')
        EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
        EMAIL_USE_TLS = smtpSettings.get('useTLS', True)
        EMAIL_USE_SSL = smtpSettings.get('useSSL', False)
    except Exception as e:
        logger.error(f"Erreur lors de la lecture du fichier de configuration SMTP : {e}")
else:
    logger.error(f"Fichier de configuration SMTP introuvable : {smtp_config_file}")

DOCUMENT_DIR = 'documents'

# Configuration CORS temporaire pour debug
CORS_ALLOW_ALL_HEADERS = True
CORS_ALLOW_CREDENTIALS = True

# Configuration CORS spécifique pour la production
CORS_ALLOWED_ORIGINS = os.getenv('CORS_ALLOWED_ORIGINS', 'http://localhost:3000,http://localhost:8080,http://127.0.0.1:3000,http://127.0.0.1:8080').split(',')


CORS_ALLOW_HEADERS = [
    'accept',
    'accept-encoding',
    'authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
    'X-Auth-Token',
]

# Méthodes HTTP autorisées
CORS_ALLOWED_METHODS = [
    'DELETE',
    'GET',
    'OPTIONS',
    'PATCH',
    'POST',
    'PUT',
]

CSRF_TRUSTED_ORIGINS = os.getenv('CSRF_TRUSTED_ORIGINS', 'http://localhost:3000,http://localhost:8080').split(',')

CSRF_COOKIE_HTTPONLY = False
CSRF_COOKIE_SECURE = False
CSRF_COOKIE_NAME = 'csrftoken'

USE_TZ = True
TZ_APPLI = 'Europe/Paris'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        "NAME": "school",
        "USER": "postgres",
        "PASSWORD": "postgres",
        "HOST": "database",
        "PORT": "5432",
    }
}

AUTH_USER_MODEL = 'Auth.Profile'
AUTHENTICATION_BACKENDS = ('Auth.backends.EmailBackend', )
SILENCED_SYSTEM_CHECKS = ["auth.W004"]

EXPIRATION_URL_NB_DAYS = 7
EXPIRATION_DI_NB_DAYS = 20
DATE_FORMAT = '%d-%m-%Y %H:%M'

EXPIRATION_SESSION_NB_SEC = 10

NB_RESULT_SUBSCRIPTIONS_PER_PAGE = 8
NB_RESULT_PROFILES_PER_PAGE = 15
NB_MAX_PAGE = 100

REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'Subscriptions.pagination.CustomSubscriptionPagination',
    'PAGE_SIZE': NB_RESULT_SUBSCRIPTIONS_PER_PAGE,
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_simplejwt.authentication.JWTAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ),
}

CELERY_BROKER_URL = 'redis://redis:6379/0'
CELERY_RESULT_BACKEND = 'redis://redis:6379/0'
CELERY_ACCEPT_CONTENT = ['json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TIMEZONE = 'Europe/Paris'
CELERY_BROKER_CONNECTION_RETRY_ON_STARTUP = True

URL_DJANGO = 'http://localhost:8080/'

REDIS_HOST = 'redis'
REDIS_PORT = 6379
REDIS_DB = 0
REDIS_PASSWORD = None

SECRET_KEY = 'QWQ8bYlCz1NpQ9G0vR5kxMnvWszfH2y3'
SIMPLE_JWT = {
    'ACCESS_TOKEN_LIFETIME': timedelta(minutes=15),
    'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
    'ROTATE_REFRESH_TOKENS': False,
    'BLACKLIST_AFTER_ROTATION': True,
    'ALGORITHM': 'HS256',
    'SIGNING_KEY': SECRET_KEY,
    'VERIFYING_KEY': None,
    'AUTH_HEADER_TYPES': ('Bearer',),
    'USER_ID_FIELD': 'id',
    'USER_ID_CLAIM': 'user_id',
    'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',),
    'TOKEN_TYPE_CLAIM': 'token_type',
}

# Configuration for DocuSeal JWT
DOCUSEAL_JWT = {
    'ALGORITHM': 'HS256',
    'SIGNING_KEY': SECRET_KEY,
    'EXPIRATION_DELTA': timedelta(hours=1)
}

# Django Channels Configuration
ASGI_APPLICATION = 'N3wtSchool.asgi.application'

CHANNEL_LAYERS = {
    'default': {
        'BACKEND': 'channels_redis.core.RedisChannelLayer',
        'CONFIG': {
            "hosts": [('redis', 6379)],
        },
    },
}