"""
Django settings for devart project.

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

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 os
from dotenv import load_dotenv

import devart.context_processor

# Charger les variables d'environnement depuis le fichier .env
load_dotenv()

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# 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 = os.getenv('SECRET_KEY')

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = os.getenv('DEBUG') == 'True'

ALLOWED_HOSTS = os.getenv('ALLOWED_HOSTS').split(',')
CSRF_TRUSTED_ORIGINS = os.getenv('CSRF_TRUSTED_ORIGINS').split(',')
USE_X_FORWARDED_HOST = os.getenv('USE_X_FORWARDED_HOST') == 'True'
SECURE_PROXY_SSL_HEADER = tuple(os.getenv('SECURE_PROXY_SSL_HEADER').split(','))

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'core',
    'courses',
    'users',
]

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 = 'devart.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / 'templates'],  # Correction de l'emplacement des templates
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',

                'devart.context_processor.app_version',
                'core.context_processor.site_settings',
                'courses.context_processors.course_list',
            ],
        },
    },
]

WSGI_APPLICATION = 'devart.wsgi.application'


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

DATABASES = {
    'default': {
        'ENGINE': os.environ.get('DATABASE_ENGINE'),
        'USER': os.environ.get('DATABASE_USER'),
        'PASSWORD': os.environ.get('DATABASE_PASSWORD'),
        'HOST': os.environ.get('DATABASE_HOST'),
        'PORT': os.environ.get('DATABASE_PORT'),
    }
}

# La partie intelligente :
db_name = os.environ.get('DATABASE_NAME')
db_engine = DATABASES['default']['ENGINE']

if 'sqlite' in db_engine:
    # Si c'est SQLite, on ajoute le chemin complet
    DATABASES['default']['NAME'] = BASE_DIR / db_name
else:
    # Si c'est MySQL (ou Postgres), on met juste le nom de la base
    DATABASES['default']['NAME'] = db_name


# 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',
    },
    {
        '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 = 'fr-FR'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


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

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]

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

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

# On défini une fonction qui va s'occuper de récupérer la version actuelle de l'application
def get_git_version():
    import subprocess
    """
        DEV : Calcule la version Git et met à jour le fichier VERSION.txt
        PROD : Lit simplement le fichier VERSION.txt
        """
    version_file = os.path.join(BASE_DIR, 'VERSION.txt')

    # --- CAS 1 : MODE DÉVELOPPEMENT (Mise à jour du fichier) ---
    if DEBUG:
        try:
            # 1. On récupère les infos Git
            hash_part = subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD'],
                                                stderr=subprocess.DEVNULL).strip().decode('utf-8')

            try:
                tag_part = subprocess.check_output(["git", "describe", "--tags", "--abbrev=0"],
                                                   stderr=subprocess.DEVNULL).strip().decode('utf-8')
            except:
                tag_part = "v0.0.x"  # Fallback si pas de tag

            full_version = f"{tag_part} ({hash_part})"

            # 2. On ÉCRIT/MET À JOUR le fichier texte
            with open(version_file, 'w') as f:
                f.write(full_version)

            return full_version

        except Exception as e:
            # Si Git échoue en local (rare, mais possible)
            return f"Dev Mode (Err: {e})"

    # --- CAS 2 : MODE PRODUCTION (Lecture seule) ---
    else:
        if os.path.exists(version_file):
            with open(version_file, 'r') as f:
                return f.read().strip()
        else:
            return "Version inconnue (Fichier manquant)"

GIT_VERSION = get_git_version()