"""
Django settings for novawow project.

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

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

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

from pathlib import Path
import os

from dotenv import load_dotenv

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

# Carga las variables de entorno desde un archivo .env (no versionado)
load_dotenv(BASE_DIR / '.env')


def _env_bool(name, default=False):
    """Lee una variable de entorno booleana ('1', 'true', 'yes', 'on')."""
    return os.getenv(name, str(default)).lower() in ('1', 'true', 'yes', 'on')


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/5.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.getenv('DJANGO_SECRET_KEY', 'django-insecure-dev-key-change-me')

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = _env_bool('DJANGO_DEBUG', False)

if not DEBUG:
    ALLOWED_HOSTS = ['novawow.com', 'www.novawow.com', '95.216.107.200', 'localhost', '127.0.0.1']
    SECURE_SSL_REDIRECT = False
    SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
    SECURE_HSTS_SECONDS = 31536000  # Habilita HSTS por 1 año
    SECURE_HSTS_INCLUDE_SUBDOMAINS = True
    SECURE_HSTS_PRELOAD = True
    SESSION_COOKIE_SECURE = True
    CSRF_COOKIE_SECURE = True
else:
    # Modo desarrollo, no se aplican configuraciones de seguridad
    ALLOWED_HOSTS = ['localhost', '127.0.0.1', 'novawow.com', 'www.novawow.com']
    SECURE_SSL_REDIRECT = False
    SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
    SECURE_HSTS_SECONDS = 0
    SECURE_HSTS_INCLUDE_SUBDOMAINS = False
    SECURE_HSTS_PRELOAD = False
    SESSION_COOKIE_SECURE = False
    CSRF_COOKIE_SECURE = False
    
    
CSRF_TRUSTED_ORIGINS = [
    "https://www.novawow.com",
    "https://novawow.com"
]

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'home',
    'django_ckeditor_5',
    'django_extensions',
    'wotlk_db',
    'forum',
]

# Configuración para AC SOAP
AC_SOAP_URL = os.getenv('AC_SOAP_URL', 'http://127.0.0.1:2079')
AC_SOAP_USER = os.getenv('AC_SOAP_USER', 'AC_SOAP')
AC_SOAP_PASSWORD = os.getenv('AC_SOAP_PASSWORD', '')
AC_SOAP_URN = os.getenv('AC_SOAP_URN', 'urn:AC')


# Configuración de SumUp
SUMUP_CLIENT_ID = os.getenv('SUMUP_CLIENT_ID', '')
SUMUP_CLIENT_SECRET = os.getenv('SUMUP_CLIENT_SECRET', '')
SUMUP_MERCHANT_EMAIL = os.getenv('SUMUP_MERCHANT_EMAIL', '')
SUMUP_CURRENCY = os.getenv('SUMUP_CURRENCY', 'EUR')  # Puedes cambiarlo si necesitas otra moneda


# Configuración del correo electrónico para SMTP de Gmail
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = os.getenv('EMAIL_HOST', 'smtp.gmail.com')
EMAIL_PORT = int(os.getenv('EMAIL_PORT', '587'))
EMAIL_USE_TLS = _env_bool('EMAIL_USE_TLS', True)
EMAIL_USE_SSL = _env_bool('EMAIL_USE_SSL', False)
EMAIL_HOST_USER = os.getenv('EMAIL_HOST_USER', '')
EMAIL_HOST_PASSWORD = os.getenv('EMAIL_HOST_PASSWORD', '')  # App Password de Gmail
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER

 
CKEDITOR_5_CONFIGS = {
    'default': {
        'toolbar': [
            'heading', '|', 'bold', 'italic', 'underline', 'link', 'bulletedList', 'numberedList', 
            '|', 'alignment', 'outdent', 'indent', '|', 'blockQuote', 'codeBlock', 
            'insertTable', 'mediaEmbed', '|', 'undo', 'redo'
        ],
        'height': '400px',
        'width': '100%',
        'language': 'es',
        'table': {
            'contentToolbar': [
                'tableColumn', 'tableRow', 'mergeTableCells'
            ]
        },
        'mediaEmbed': {
            'previewsInData': True
        },
    }
}


CSP_FRAME_SRC = [
    "https://www.youtube.com",
    "https://www.youtube.com/embed/",
]
CSP_DEFAULT_SRC = ["'self'", "https://www.youtube.com"]

X_FRAME_OPTIONS = 'SAMEORIGIN'
SECURE_CONTENT_TYPE_NOSNIFF = False



MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.locale.LocaleMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'home.middleware.MaintenanceMiddleware',
]

ROOT_URLCONF = 'novawow.urls'

URL_PRINCIPAL = 'http://127.0.0.1:8000'

# Nombre del servidor
NOMBRE_SERVIDOR = "Nova WoW"

SESSION_ENGINE = 'django.contrib.sessions.backends.db'
SESSION_COOKIE_NAME = 'novawow_session'
SESSION_COOKIE_HTTPONLY = True
SESSION_EXPIRE_AT_BROWSER_CLOSE = False
SESSION_COOKIE_AGE = 3600  # 1 hora

# Año actual
from datetime import datetime
ANIO_ACTUAL = datetime.now().year

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',
                'home.context_processors.url_principal',
                'home.context_processors.configuracion_global',
                'home.context_processors.get_server_info',
            ],
        },
    },
]

STRIPE_PUBLIC_KEY = os.getenv('STRIPE_PUBLIC_KEY', '')
STRIPE_SECRET_KEY = os.getenv('STRIPE_SECRET_KEY', '')
STRIPE_WEBHOOK_SECRET = os.getenv('STRIPE_WEBHOOK_SECRET', '')


WSGI_APPLICATION = 'novawow.wsgi.application'


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

# Credenciales MySQL compartidas por todas las bases de datos
DB_USER = os.getenv('DB_USER', '')
DB_PASSWORD = os.getenv('DB_PASSWORD', '')
DB_HOST = os.getenv('DB_HOST', '127.0.0.1')
DB_PORT = os.getenv('DB_PORT', '3306')

_ACORE_OPTIONS = {'init_command': "SET sql_mode='STRICT_TRANS_TABLES'"}


def _mysql_db(name, options=None):
    conf = {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': name,
        'USER': DB_USER,
        'PASSWORD': DB_PASSWORD,
        'HOST': DB_HOST,
        'PORT': DB_PORT,
    }
    if options:
        conf['OPTIONS'] = options
    return conf


DATABASES = {
    'default': _mysql_db(os.getenv('DB_NAME_DEFAULT', 'django_wow')),
    'acore_auth': _mysql_db(os.getenv('DB_NAME_AUTH', 'acore_auth'), _ACORE_OPTIONS),
    'acore_characters': _mysql_db(os.getenv('DB_NAME_CHARACTERS', 'acore_characters'), _ACORE_OPTIONS),
    'acore_world': _mysql_db(os.getenv('DB_NAME_WORLD', 'acore_world'), _ACORE_OPTIONS),
    # Base de datos del portal web (foro, etc.)
    'acore_web': _mysql_db(os.getenv('DB_NAME_WEB', 'acore_web'), _ACORE_OPTIONS),
}

# Nivel GM mínimo (acore_auth.account_access.gmlevel) para moderar el foro
FORUM_MOD_GMLEVEL = int(os.getenv('FORUM_MOD_GMLEVEL', '2'))
# Tamaños de página del foro
FORUM_TOPICS_PER_PAGE = int(os.getenv('FORUM_TOPICS_PER_PAGE', '20'))
FORUM_POSTS_PER_PAGE = int(os.getenv('FORUM_POSTS_PER_PAGE', '15'))


AC_LOGON = None

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

LANGUAGES = [
    ('es', 'Español'),
    # Agrega otros idiomas aquí si los necesitas
    # ('en', 'English'),
]

LANGUAGE_CODE = 'es'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


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

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

# Directorios adicionales donde buscar archivos estáticos
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static'),
]

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

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
