"""
Django settings for VorgabenUI project.

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

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

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

import os
from pathlib import Path

# 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.2/howto/deployment/checklist/

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = os.environ.get('DEBUG', 'True').lower() in ('true', '1', 'yes', 'on')

# Application version (from ConfigMap)
VERSION = os.environ.get('VERSION', '0.0.0')

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get('VORGABENUI_SECRET')
if not SECRET_KEY:
    # Check if we're in a build environment (Docker build, CI, etc.)
    is_build_env = any([
        os.environ.get('DOCKER_BUILDKIT'),  # Docker build
        os.environ.get('CI'),               # CI environment
        os.environ.get('GITHUB_ACTIONS'),   # GitHub Actions
        os.environ.get('GITEA_ACTIONS'),    # Gitea Actions
    ])
    
    # Use DEBUG environment variable or assume debug mode for local development
    debug_mode = os.environ.get('DEBUG', 'True').lower() in ('true', '1', 'yes', 'on')
    
    if debug_mode or is_build_env:
        # Fixed fallback key for local development and build environments
        SECRET_KEY = 'dev-fallback-key-for-local-debugging-only-not-for-production-use-12345'
        if not is_build_env:  # Don't log during build to avoid noise
            import logging
            logging.warning("🚨 Using fallback SECRET_KEY for local development. This should NEVER happen in production!")
    else:
        raise ValueError("VORGABENUI_SECRET environment variable is required")


ALLOWED_HOSTS = os.environ.get('DJANGO_ALLOWED_HOSTS', "10.128.128.144,localhost,127.0.0.1,*").split(",")

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'whitenoise',
    'dokumente',
    'abschnitte',
    'stichworte',
    'referenzen',
    'rollen',
    'mptt',
    'pages',
    'nested_admin',
]

MIDDLEWARE = [
    'whitenoise.middleware.WhiteNoiseMiddleware',
    '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',
]

INTERNAL_IPS = [ "127.0.0.1","10.128.128.130"]

ROOT_URLCONF = 'VorgabenUI.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'VorgabenUI.context_processors.version',
            ],
        },
    },
]

WSGI_APPLICATION = 'VorgabenUI.wsgi.application'

CSRF_TRUSTED_ORIGINS=["https://vorgabenportal.knowyoursecurity.com"]

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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'data/db.sqlite3',
    }
}


# Password validation
# https://docs.djangoproject.com/en/5.2/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.2/topics/i18n/

LANGUAGE_CODE = 'de-ch'

TIME_ZONE = 'Europe/Zurich'

USE_I18N = True

USE_TZ = True


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

STATIC_URL = '/static/'
#STATIC_ROOT="/home/adebaumann/VorgabenUI/staticfiles/"
STATIC_ROOT="staticfiles/"
STATICFILES_DIRS= (
    os.path.join(BASE_DIR,"static"),
    )

# Media files (User-uploaded content)
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

# Diagram cache settings
DIAGRAM_CACHE_DIR = 'diagram_cache'  # relative to MEDIA_ROOT

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

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

# Custom error pages
handler400 = 'pages.views.custom_400'
handler403 = 'pages.views.custom_403'
handler404 = 'pages.views.custom_404'
handler500 = 'pages.views.custom_500'
DATA_UPLOAD_MAX_NUMBER_FIELDS=10250
NESTED_ADMIN_LAZY_INLINES = True

# Authentication settings
LOGIN_URL = 'login'
LOGIN_REDIRECT_URL = '/'
LOGOUT_REDIRECT_URL = 'login'

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

#LOGGING = {
#    "version": 1,
#    "handlers"  :{
#        "file": {
#            "class": "logging.FileHandler",
#            "filename": "general.log",
#            "level": "DEBUG",
#        },
#    },
#}
