"""
Django settings for scrapyproject project.

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

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
import environ

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

env = environ.Env()
environ.Env.read_env(os.path.join(BASE_DIR, '.env')) 

# 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-#$kw&+(+18p(3v+)a_f#4&n7^i=vj&)m7z3(wk00bt!f4-ua&9'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = env.bool('DEBUG', default=False)

# ALLOWED_HOSTS = []
# Set ALLOWED_HOSTS from .env
ALLOWED_HOSTS = env.list('ALLOWED_HOSTS', default=['127.0.0.1', 'localhost'])

# Function to add both 'http://' and 'https://' to each allowed host
def get_csrf_trusted_origins(allowed_hosts):
    origins = []
    for host in allowed_hosts:
        if host not in ['localhost', '127.0.0.1']:  # Add schemes for external hosts
            origins.append(f'https://{host}')
        origins.append(f'http://{host}')
    return origins

# Use the function to set CSRF_TRUSTED_ORIGINS
CSRF_TRUSTED_ORIGINS = get_csrf_trusted_origins(ALLOWED_HOSTS)
# Application definition

INSTALLED_APPS = [

    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'authapp',
    'spidersweb',

]

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

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / 'templates',
                 # Add the core templates directory so it can be accessed globally
                os.path.join(BASE_DIR, 'core/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 = 'scrapyproject.wsgi.application'


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

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


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

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

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'


DATABASES = {
    'default': {
        #'ENGINE': env('DB_ENGINE'),
        'ENGINE': 'mysql.connector.django',
        'NAME': env('DB_NAME'),  # Replace with your database name
        'USER': env('DB_USER'),  # Replace with your MySQL username
        'PASSWORD': env('DB_PASSWORD'),  # Replace with your MySQL password
        'HOST': env('DB_HOST', default='localhost'),  # Optional default
        'PORT': env('DB_PORT', default='3306'),  # Optional default

        'OPTIONS': {
            'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",
        },
        'POOL_OPTIONS': {
            'MAX_CONNS': 20,  # Set max number of connections
            'MIN_CONNS': 5,   # Set min number of connections
        }
    }
}

SELENIUM_DRIVER_EXECUTABLE_PATH = '/usr/bin/chromedriver'  # Update with the path to your WebDriver
GRID_IP = env('GRID_IP')

LOGIN_URL = 'login'
LOGIN_REDIRECT_URL = 'home'  # Redirect to homepage after login
LOGOUT_REDIRECT_URL = 'login'  # Redirect to login after logout

# Define BASE_DIR the old way
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Path to the static folder
static_dir = os.path.join(BASE_DIR, "static")

# Check if the static directory exists, if not, create it
if not os.path.exists(static_dir):
    os.makedirs(static_dir)

# Update STATICFILES_DIRS
STATICFILES_DIRS = [
    static_dir,  # Root-level static folder
]

# Update STATIC_ROOT
STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")

# Basic Django settings

EMAIL_BACKEND = env('EMAIL_BACKEND', default='django.core.mail.backends.smtp.EmailBackend')  # Default backend
EMAIL_HOST = env('EMAIL_HOST', default='localhost')  # Default host
EMAIL_PORT = env.int('EMAIL_PORT', default=587)  # Default port for TLS
EMAIL_USE_TLS = env.bool('EMAIL_USE_TLS', default=True)  # Default to True
EMAIL_HOST_USER = env('EMAIL_HOST_USER', default='')  # Default empty
EMAIL_HOST_PASSWORD = env('EMAIL_HOST_PASSWORD', default='')  # Default empty
DEFAULT_FROM_EMAIL = env('DEFAULT_FROM_EMAIL', default='webmaster@localhost')  # Default email

# logging
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': '{levelname} {asctime} {module} {message}',
            'style': '{',
        },
        'simple': {
            'format': '{levelname} {message}',
            'style': '{',
        },
    },
    'handlers': {
        'file': {
            'level': 'INFO',  # Log only INFO, WARNING, ERROR, CRITICAL levels
            'class': 'logging.FileHandler',
            'filename': os.path.join(BASE_DIR, 'django_info.log'),  # Save logs to a file
            'formatter': 'verbose',
        },
        'console': {
            'level': 'INFO',  # Log only INFO and above to the console
            'class': 'logging.StreamHandler',
            'formatter': 'simple',
        },
    },
    'loggers': {
        'django': {
            'handlers': ['console', 'file'],
            'level': 'INFO',  # Only log INFO and above levels
            'propagate': True,
        },
        'spidersweb': {  # Custom logger for your specific spider app
            'handlers': ['console', 'file'],
            'level': 'INFO',  # Customize levels per app
            'propagate': False,
        },
    },
}
