"""
Django settings for core project.
Architecture : Headless CMS (DRF + Next.js)
"""

import os
import sys
from pathlib import Path
import environ  # Gestion des variables d'environnement

# --- 1. INITIALISATION DE L'ENVIRONNEMENT ---
BASE_DIR = Path(__file__).resolve().parent.parent

# Ajout du dossier 'apps' au PYTHONPATH
sys.path.insert(0, os.path.join(BASE_DIR, 'apps'))

# Initialisation de django-environ
env = environ.Env(
    DEBUG=(bool, False)
)

# Lecture du fichier .env
environ.Env.read_env(os.path.join(BASE_DIR, '.env'))


# --- 2. SÉCURITÉ & CORE ---
SECRET_KEY = env('SECRET_KEY')

DEBUG = env('DEBUG')

ALLOWED_HOSTS = env.list('ALLOWED_HOSTS', default=[])


# --- 3. APPLICATIONS INSTALLÉES ---
INSTALLED_APPS = [
    # Django Default
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    # --- Third Party Apps ---
    'rest_framework',           # API Engine
    'corsheaders',              # Communication avec Next.js
    'django_json_widget',       # Éditeur JSON pour l'admin
    'adminsortable2',           # Drag & Drop dans l'admin

    # --- Local Apps (Domain Driven) ---
    'apps.users',               # Custom User Model
    'apps.pages',               # CMS Pages
    'apps.sections',            # CMS Sections (Contenu modulaire)
    'apps.content',             # Blog / Projets
    'apps.navigation',          # Menus
    'apps.settings_site',       # Footer / Global Settings
    'apps.chatbot',             # IA Core
]

# --- 4. MIDDLEWARE ---
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',
]

ROOT_URLCONF = 'core.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 = 'core.wsgi.application'


# --- 5. BASE DE DONNÉES ---
DATABASES = {
    'default': env.db()
}


# --- 6. AUTHENTIFICATION ---
# Modèle utilisateur personnalisé
AUTH_USER_MODEL = 'users.User'

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',
    },
]


# --- 7. API CONFIGURATION (DRF) ---
REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticatedOrReadOnly',
    ],
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication',
    ],
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
    'PAGE_SIZE': 20,
    'DATETIME_FORMAT': "%Y-%m-%d %H:%M:%S",
}

# --- 8. CORS CONFIGURATION (NEXT.JS) ---
CORS_ALLOWED_ORIGINS = env.list('CORS_ALLOWED_ORIGINS', default=["http://localhost:3000"])
CORS_ALLOW_CREDENTIALS = True


# --- 9. INTERNATIONALISATION ---
LANGUAGE_CODE = 'fr-fr'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True


# --- 10. FICHIERS STATIQUES & MEDIA ---
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

# --- 11. CONFIGURATION IA (CHATBOT) ---
OPENROUTER_API_KEY = env('OPENROUTER_API_KEY', default='')
OPENROUTER_MODEL = env('OPENROUTER_MODEL', default='cognitivecomputations/dolphin-mistral-24b-venice-edition:free')