"""
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: don't run with debug turned on in production!
DEBUG = os.getenv('DJANGO_DEBUG', 'False').lower() in ('true', '1')

ALLOWED_HOSTS = os.getenv('ALLOWED_HOSTS', 'localhost,127.0.0.1').split(',')

# 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',
    'rest_framework_simplejwt.token_blacklist',
    '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
        },
        "file": {
            "level": "WARNING",
            "class": "logging.FileHandler",
            "filename": os.path.join(BASE_DIR, "django.log"),
            "formatter": "verbose",
        },
    },
    "root": {
        "handlers": ["console", "file"],
        "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,
        },
        # Logs JWT : montre exactement pourquoi un token est rejeté (expiré,
        # signature invalide, claim manquant, etc.)
        "rest_framework_simplejwt": {
            "handlers": ["console"],
            "level": os.getenv("JWT_LOG_LEVEL", "DEBUG"),
            "propagate": False,
        },
        "rest_framework": {
            "handlers": ["console"],
            "level": os.getenv("DRF_LOG_LEVEL", "WARNING"),
            "propagate": False,
        },
    },
}

# Hashage des mots de passe - configuration explicite pour garantir un stockage sécurisé
# Les mots de passe ne sont JAMAIS stockés en clair
PASSWORD_HASHERS = [
    'django.contrib.auth.hashers.PBKDF2PasswordHasher',
    'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
    'django.contrib.auth.hashers.Argon2PasswordHasher',
    'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
    'django.contrib.auth.hashers.ScryptPasswordHasher',
]

# 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': 10,
        }
    },
    {
        '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/

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 ##############################
########################################################################


# Configuration de l'email de l'application
EMAIL_HOST = os.getenv('EMAIL_HOST', 'smtp.example.com')
EMAIL_PORT = os.getenv('EMAIL_PORT', 587)
EMAIL_HOST_USER = os.getenv('EMAIL_HOST_USER', '')
EMAIL_HOST_PASSWORD = os.getenv('EMAIL_HOST_PASSWORD', '')
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = os.getenv('EMAIL_USE_TLS', 'true').lower() == 'true'
EMAIL_USE_SSL = os.getenv('EMAIL_USE_SSL', 'false').lower() == 'true'

DOCUMENT_DIR = 'documents'

# Configuration CORS temporaire pour debug
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 = os.getenv('CSRF_COOKIE_SECURE', 'false').lower() == 'true'
CSRF_COOKIE_NAME = 'csrftoken'
CSRF_COOKIE_DOMAIN = os.getenv('CSRF_COOKIE_DOMAIN', '')

# --- Sécurité des cookies et HTTPS (activer en production via variables d'env) ---
SESSION_COOKIE_SECURE = os.getenv('SESSION_COOKIE_SECURE', 'false').lower() == 'true'
SESSION_COOKIE_HTTPONLY = True
SESSION_COOKIE_SAMESITE = 'Lax'
SECURE_CONTENT_TYPE_NOSNIFF = True
SECURE_HSTS_SECONDS = int(os.getenv('SECURE_HSTS_SECONDS', '0'))
SECURE_HSTS_INCLUDE_SUBDOMAINS = os.getenv('SECURE_HSTS_INCLUDE_SUBDOMAINS', 'false').lower() == 'true'
SECURE_HSTS_PRELOAD = os.getenv('SECURE_HSTS_PRELOAD', 'false').lower() == 'true'
SECURE_SSL_REDIRECT = os.getenv('SECURE_SSL_REDIRECT', 'false').lower() == 'true'

USE_TZ = True
TZ_APPLI = 'Europe/Paris'

DB_NAME = os.getenv('DB_NAME', 'school')
DB_USER = os.getenv('DB_USER', 'postgres')
DB_PASSWORD = os.getenv('DB_PASSWORD', 'postgres')
DB_HOST = os.getenv('DB_HOST', 'database')
DB_PORT = os.getenv('DB_PORT', '5432')
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        "NAME": DB_NAME,
        "USER": DB_USER,
        "PASSWORD": DB_PASSWORD,
        "HOST": DB_HOST,
        "PORT": DB_PORT,
    }
}

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_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated',
    ],
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'Auth.backends.LoggingJWTAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ),
    'DEFAULT_THROTTLE_CLASSES': [
        'rest_framework.throttling.AnonRateThrottle',
        'rest_framework.throttling.UserRateThrottle',
    ],
    'DEFAULT_THROTTLE_RATES': {
        'anon': '100/min',
        'user': '1000/min',
        'login': '10/min',
    },
}

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 = os.getenv('URL_DJANGO', 'http://localhost:8080/')

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

_secret_key_default = '<SECRET_KEY>'
_secret_key = os.getenv('SECRET_KEY', _secret_key_default)
if _secret_key == _secret_key_default and not DEBUG:
    raise ValueError(
        "La variable d'environnement SECRET_KEY doit être définie en production. "
        "Utilisez une clé aléatoire forte (ex: python -c 'import secrets; print(secrets.token_hex(50))')."
    )
SECRET_KEY = _secret_key

_webhook_api_key_default = '<WEBHOOK_API_KEY>'
_webhook_api_key = os.getenv('WEBHOOK_API_KEY', _webhook_api_key_default)
if _webhook_api_key == _webhook_api_key_default and not DEBUG:
    raise ValueError(
        "La variable d'environnement WEBHOOK_API_KEY doit être définie en production. "
        "Utilisez une clé aléatoire forte (ex: python -c 'import secrets; print(secrets.token_hex(50))')."
    )
WEBHOOK_API_KEY = _webhook_api_key

SIMPLE_JWT = {
    'ACCESS_TOKEN_LIFETIME': timedelta(minutes=15),
    'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
    'ROTATE_REFRESH_TOKENS': True,
    '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': 'type',
}

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

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