"""
Django settings for sweetvilla project.

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

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
#load doetenv
from dotenv import load_dotenv # type: ignore
load_dotenv()


# for mysql support
import pymysql
pymysql.install_as_MySQLdb()


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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-l)lw$h(s3o6pedjy+#s!v++*0-qecvzk5&6%a&!ya!0rlbs%w$'

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

ALLOWED_HOSTS = ['admin.sweetvilla.in', 'www.admin.sweetvilla.in', 'pg.sweetvilla.in']

if DEBUG:
    ALLOWED_HOSTS += ['localhost', '127.0.0.1']


# Application definition

INSTALLED_APPS = [
    'admin_interface',
    'colorfield',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    "whitenoise.runserver_nostatic",
    'django.contrib.staticfiles',
    'utils',
    'hostel',
    'room',
    'meal',
    'address',
    'tenant',
    'paymentlog'
]

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

STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"

ROOT_URLCONF = 'sweetvilla.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',
            ],
        },
    },
]

WSGI_APPLICATION = 'sweetvilla.wsgi.application'


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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': os.environ.get("DATABASE_NAME", ''),
        'USER': os.environ.get("DATABASE_USER", 'root'),
        'PASSWORD': os.environ.get("DATABASE_PASSWORD", ''),
        'HOST': os.environ.get("DATABASE_HOST", 'localhost'),
        'PORT': os.environ.get("DATABASE_PORT", '3306'),
        'OPTIONS': {
            'charset': 'utf8mb4',      # Ensures proper Unicode support
            'init_command': "SET time_zone='Asia/Kolkata'",
        }
    }
}


# 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/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'Asia/Kolkata'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.1/howto/static-files/
#FORCE_SCRIPT_NAME = '/new/'
STATIC_URL = 'static/'
STATIC_ROOT = 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'

# to support file upload
MEDIA_URL = 'media/'
MEDIA_ROOT = BASE_DIR / 'media'


# logging behavior development
APP_LOG_FILENAME=os.path.join(BASE_DIR, 'logs/app.log')
ERROR_LOG_FILENAME=os.path.join(BASE_DIR, 'logs/error.log')

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': '{levelname} {asctime} {module} {process:d} {thread:d} {message}',
            'style': '{',
        },
        'simple': {
            'format': '{levelname} {message}',
            'style': '{',
        },
    },
    'handlers': {
        'app_file': {
            'level': 'INFO',  # Log INFO and above to app.log
            'class': 'logging.FileHandler',
            'filename': APP_LOG_FILENAME,
            'formatter': 'verbose',
            'filters': ['require_not_error']  # Filter to exclude ERROR and CRITICAL logs
        },
        'error_file': {
            'level': 'ERROR', # Log ERROR and CRITICAL to error.log
            'class': 'logging.FileHandler',
            'filename': ERROR_LOG_FILENAME,
            'formatter': 'verbose'
        },
        'console': {
            'level': 'DEBUG',  # Log DEBUG and above to console (can be adjusted)
            'class': 'logging.StreamHandler',
            'formatter': 'verbose',
        },
    },
    'loggers': {
        '': {  # Root logger (catches everything)
            'handlers': ['app_file', 'error_file', 'console'],  # Use both file handlers and the console
            'level': 'DEBUG', # Set the minimum level for the root logger
            'propagate': True,
        },
        # Optional:  Specific loggers for your apps (e.g., 'myapp', 'auth')
        #  You can customize the handlers and level for each app individually.
        # 'myapp': {
        #     'handlers': ['app_file', 'error_file'], #  or just ['app_file'], etc.
        #     'level': 'INFO', #  or DEBUG, WARNING, etc.
        #     'propagate': True,  #  Whether to propagate to the root logger (usually True)
        # },
    },
   'filters': {
        'require_not_error': {
            '()': 'utils.logging_filters.RequireNotError',  # Use the custom filter
        },
    },
}
