"""
Django settings for misfinanzas 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
from .logging import LOGGING

APP_NAME = "Finanzas"
APP_VERSION = os.environ.get("APP_VERSION", "17.0.10")  # Valor por defecto si no está definido
IMG_VERSION = os.environ.get("IMG_VERSION", "0.0.0-dev")  # Valor por defecto si no está definido


# 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: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-^9*3@g$5brgjmhv&h!h*)c9kp)8i5tnqee_eu+fi728@g96#8&'

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

ALLOWED_HOSTS = [".reymota.es", ".reymota.lab", "127.0.0.1", "localhost", "k8s-server"]

CSRF_TRUSTED_ORIGINS = ["https://*.reymota.es", "http://*.reymota.lab", "http://k8s-server"]


# Application definition

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

    'finanzas',
    'reymotausers',

    'rest_framework',
]

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

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / 'templates'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'misfinanzas.context_processors.app_version',
                'misfinanzas.context_processors.debug_mode',
            ],
            'libraries': {
                'filtros_de_entorno': 'misfinanzas.templatetags.filtros_de_entorno',
            }
        },
    },
]

WSGI_APPLICATION = 'misfinanzas.wsgi.application'


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

DATABASES = {
    'default': {
        "ENGINE": "django.db.backends.postgresql",
        "NAME": "finanzas",
        "USER": "creylopez",
        "PASSWORD": "Dsa-0213",
        "HOST": "postgresql",
        "PORT": "5432",
    }
}

# 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 = 'es-es'

TIME_ZONE = 'Europe/Madrid'

USE_I18N = True

USE_TZ = True
I18N = True
L10N = True
DECIMAL_SEPARATOR = ','
THOUSAND_SEPARATOR = '.'


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

STATIC_URL = 'static/'
STATIC_ROOT = BASE_DIR / "staticfiles"
STATICFILES_DIRS = [BASE_DIR / "static",]

# Mediafiles

MEDIA_ROOT = BASE_DIR / "mediafiles"
MEDIA_URL = '/media/'

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

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

LOGIN_URL = '/accounts/login/'
LOGIN_REDIRECT_URL = 'dashboard'
LOGOUT_REDIRECT_URL = 'dashboard'

AUTH_USER_MODEL = "reymotausers.ReyMotaUser"

RECURRENTES_API_TOKEN = 'mi-token-secreto-superseguro'
# Token dedicado para la API de generación de informes PDF
# REPORTS_API_TOKEN = os.environ.get('REPORTS_API_TOKEN', 'mi-token-informes-por-defecto')

'''
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'custom_format': {
            'format': '{levelname} {asctime} {module} {message}',
            'style': '{',
        },
        'formato_personalizado': {
            'format': '[{asctime}] [{levelname}] [{module}] <<< {message} >>>',
            'style': '{',
        },
    },
    'handlers': {
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'formatter': 'formato_personalizado',
        },
        'file': {
            'level': 'INFO',
            'class': 'logging.FileHandler',
            'filename': BASE_DIR / 'django_template.log',
            'formatter': 'custom_format',
        },
    },
    'loggers': {
        'django': {
            'handlers': ['console'],
            'level': os.getenv('DJANGO_LOG_LEVEL', 'WARNING'),
        },
        'django.template': {
            'handlers': ['file'],
            'level': 'INFO',
            'propagate': True,
        },
        'finanzas': {
            'handlers': ['console'],
            'level': os.getenv('FINANZAS_LOG_LEVEL', 'INFO'),
        },
        'reymotausers': {
            'handlers': ['console'],
            'level': os.getenv('REYMOTAUSERS_LOG_LEVEL', 'INFO'),
        },
    },
}
'''

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'custom_format': {
            'format': '{levelname} {asctime} {module} {message}',
            'style': '{',
        },
        'formato_personalizado': {
            'format': '[{asctime}] [{levelname}] [{module}] <<< {message} >>>',
            'style': '{',
        },
    },
    'handlers': {
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'formatter': 'formato_personalizado',
        },
    },
    'loggers': {
        'django': {
            'handlers': ['console'],
            'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'),
        },
        'finanzas': {
            'handlers': ['console'],
            'level': 'INFO',
        }
    },
}
