import os
from pathlib import Path
from decouple import config
import dj_database_url

BASE_DIR = Path(__file__).resolve().parent.parent

# ─── SÉCURITÉ CRITIQUE ────────────────────────────────────────
# On lit les valeurs depuis le fichier .env (ou variables système)
SECRET_KEY = config('SECRET_KEY')
DEBUG = config('DEBUG', default=False, cast=bool)

# Liste des domaines autorisés (Obligatoire quand DEBUG=False)
ALLOWED_HOSTS = config('ALLOWED_HOSTS', default='127.0.0.1').split(',')

# ─── DEFINITION DES APPLICATIONS ──────────────────────────────
INSTALLED_APPS = [
    'jazzmin',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'accounts',
    'core',
    'dashboard',
    'scanner',
    'vitrine',
]

AUTH_USER_MODEL = 'accounts.CustomUser'

MIDDLEWARE = [
    '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 = 'billetterie_project.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',
                'core.context_processors.user_context_processor',
            ],
        },
    },
]

WSGI_APPLICATION = 'billetterie_project.wsgi.application'

# ─── BASE DE DONNÉES (POSTGRESQL) ─────────────────────────────
# Utilise dj_database_url pour parser l'URL du fichier .env
DATABASES = {
    'default': config(
        'DATABASE_URL',
        cast=dj_database_url.parse
    )
}

# ─── SÉCURITÉ DE PRODUCTION (HTTPS & COOKIES) ─────────────────
if not DEBUG:
    # Force la redirection HTTP vers HTTPS
    SECURE_SSL_REDIRECT = True
    # Empêche l'envoi des cookies de session sur des connexions non sécurisées
    SESSION_COOKIE_SECURE = True
    CSRF_COOKIE_SECURE = True
    # Protection contre le reniflage de type MIME
    SECURE_CONTENT_TYPE_NOSNIFF = True
    # Protection contre le clickjacking
    X_FRAME_OPTIONS = 'DENY'
    # HSTS (À activer après avoir vérifié que le HTTPS fonctionne bien)
    SECURE_HSTS_SECONDS = 31536000 # 1 an
    SECURE_HSTS_INCLUDE_SUBDOMAINS = True
    SECURE_HSTS_PRELOAD = True

# ─── INTERNATIONALISATION ─────────────────────────────────────
LANGUAGE_CODE = 'fr-fr'
TIME_ZONE = 'Africa/Porto-Novo'
USE_I18N = True
USE_L10N = True
USE_TZ = True

# ─── FICHIERS STATIQUES ET MÉDIAS ──────────────────────────────
STATIC_URL = '/static/'
STATICFILES_DIRS = [BASE_DIR / 'static']

# Dossier où collectstatic va rassembler tous les fichiers pour le serveur web
# Sur Namecheap, ce dossier sera créé à la racine de votre application
STATIC_ROOT = BASE_DIR / 'static_cdn'

MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

# ─── CONFIGURATION JAZZMIN (Inchangée mais compatible) ─────────
JAZZMIN_SETTINGS = {
    "site_title": "Billetterie Admin",
    "site_header": "Gestion Billetterie",
    "site_brand": "Billeterie Digitale",
    "welcome_sign": "Bienvenue dans l'espace de gestion",
    "copyright": "Billeterie Digitale Ltd",
    "search_model": "accounts.CustomUser",
    "topmenu_links": [
        {"name": "Accueil Site", "url": "vitrine:home", "permissions": ["auth.view_user"]},
        {"name": "Dashboard Gérant", "url": "dashboard:home", "permissions": ["accounts.is_admin"]},
    ],
    "show_sidebar": True,
    "navigation_expanded": True,
    "icons": {
        "accounts.CustomUser": "fas fa-users-cog",
        "core.Evenement": "fas fa-calendar-alt",
        "core.TypeTicket": "fas fa-tags",
        "core.Ticket": "fas fa-ticket-alt",
        "core.ScanLog": "fas fa-history",
    },
    "usermenu_links": [
        {"name": "Ouvrir le Scanner", "url": "scanner:active", "icon": "fas fa-qrcode"},
    ],
    "order_with_respect_to": ["accounts", "core", "dashboard", "scanner"],
}

JAZZMIN_UI_LOGOS = {
    "theme": "flatly",
    "dark_mode_theme": "darkly",
}