from pathlib import Path
from django.contrib.messages import constants as messages
import os
from dotenv import load_dotenv
from django.utils.translation import gettext_lazy as _

# Base Directory
BASE_DIR = Path(__file__).resolve().parent.parent

# Load Environment Variables
load_dotenv()
SECRET_KEY = os.getenv('SECRET_KEY')
if not SECRET_KEY:
    raise ValueError("The SECRET_KEY environment variable is not set!")

# Debug and Allowed Hosts
DEBUG = os.getenv('DEBUG')
import logging

logging.getLogger('django').setLevel(logging.WARNING)

ALLOWED_HOSTS = ['127.0.0.1','localhost','shirazcenter.com','www.shirazcenter.com','app2.shirazcenter.com',"panel.shirazcenter.com", "api.shirazcenter.com",'www.app2.shirazcenter.com']

# CSRF Settings
CSRF_TRUSTED_ORIGINS = [

    'https://shirazcenter.com',
    'https://www.shirazcenter.com',
    'https://app2.shirazcenter.com',
    'https://www.app2.shirazcenter.com',
]

AUTH_USER_MODEL = 'userauth.User'

CSRF_COOKIE_SECURE = True
CSRF_COOKIE_HTTPONLY = True
SESSION_COOKIE_SECURE = True
# SESSION_COOKIE_HTTPONLY = True
# Security Settings
# X_FRAME_OPTIONS = 'DENY'
# SECURE_HSTS_SECONDS = 31536000
# SECURE_HSTS_INCLUDE_SUBDOMAINS = True
# SECURE_HSTS_PRELOAD = True
SECURE_SSL_REDIRECT = os.getenv('SECURE_SSL_REDIRECT')
SECURE_CONTENT_TYPE_NOSNIFF = True

# Application Definition
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'core.apps.CoreConfig',
    'userauth.apps.UserauthConfig',
    'patient.apps.PatientConfig',
    'doctor.apps.DoctorConfig',
    'accountant.apps.AccountantConfig',
    'warehouse.apps.WarehouseConfig',
    'reservation.apps.ReservationConfig',
    'waapi.apps.WaapiConfig',

    'widget_tweaks',

]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'userauth.middleware.LoginRequiredMiddleware',
    'userauth.middleware.AccessControlMiddleware',
    'reservation.middleware.current_user_middleware.CurrentUserMiddleware',
    'core.middleware.NoCacheMiddleware',
]

ROOT_URLCONF = 'shirazClinic.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(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 = 'shirazClinic.wsgi.application'

# Database Configuration
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': os.getenv('DB_NAME'),
        'USER': os.getenv('DB_USER'),
        'PASSWORD': os.getenv('DB_PASSWORD'),
        'HOST': os.getenv('DB_HOST', 'localhost'),
        'PORT': os.getenv('DB_PORT', '5432'),
        'OPTIONS': {'options': '-c timezone=utc'},
    }
}

# Password Validation
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
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True

# Static and Media Files
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

# Login URLs
LOGIN_URL = '/accounts/login/'
LOGIN_REDIRECT_URL = '/dashboard/'
LOGOUT_REDIRECT_URL = '/accounts/login/'

# Default Primary Key Field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

# Caching Configuration
CACHES = {
    'default': {
        # 'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
        'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
        'LOCATION': '/home/shirazce/public_html/api.shirazcenter.com/app_shiraz_center/cache',
    }
}

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {'format': '{levelname} {asctime} {module} {message}', 'style': '{'},
        'simple': {'format': '{levelname} {message}', 'style': '{'},
    },
    'handlers': {
        'file': {
            'level': 'WARNING',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': os.path.join(BASE_DIR, 'logs/django.log'),
            'formatter': 'verbose',
            'maxBytes': 1024 * 1024 * 5,
            'backupCount': 5,
        },
        'error_file': {
            'level': 'ERROR',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': os.path.join(BASE_DIR, 'logs/django_errors.log'),
            'formatter': 'verbose',
            'maxBytes': 1024 * 1024 * 5,
            'backupCount': 5,
        },
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'formatter': 'simple',
        },
    },
    'loggers': {
        'django': {
            'handlers': ['file', 'console'],
            'level': 'INFO',
            'propagate': True,
        },
        'django.request': {
            'handlers': ['error_file', 'console'],  # هم به فایل بره هم رو کنسول ببینی
            'level': 'ERROR',  # اینجا INFO نباشه، باید ERROR باشه
            'propagate': False,
        },
        # 'django': {
        #             'handlers': ['console'],
        #             'level': 'ERROR',  # فقط خطاها
        #             'propagate': True,
        #         },
        #         'django.db.backends': {
        #             'level': 'ERROR',  # غیرفعال کردن لاگ‌های SQL
        #             'handlers': ['console'],
        #             'propagate': False,
        #         },
        #         'numpy': {
        #             'level': 'ERROR',  # غیرفعال کردن لاگ‌های numpy
        #             'handlers': ['console'],
        #             'propagate': False,
        #         },
        #         'PIL': {
        #             'level': 'ERROR',  # غیرفعال کردن لاگ‌های PIL
        #             'handlers': ['console'],
        #             'propagate': False,
        #         },
    },
}

# WAAPI_API_KEY = "RaJNAw1WpinpYHPkgbspgXaTpwwi0pLIBPm0yXN8f3d680e6"
# WASENDER_API_KEY="7c954558fdd4cd3db93f2e510fdad476304abd697dd7cca714e0af6c855c9bb0"# khom
WASENDER_API_KEY="b6df3e71c42eba5c8497af9266c41704d6c20af7538ae4ff64f1badf6c9cbf0c" # moradi
WHATSAPP_BATCH_SIZE = 3
WHATSAPP_DELAY_BETWEEN_MESSAGES = 2
WHATSAPP_DELAY_BETWEEN_BATCHES = 5
WHATSAPP_ADMIN_EMAILS = ['quick.k1399@gmail.com']
INSTANCE_ID = "73726"
MANAGER_PHONE = "9647500798989"  # شماره مدیر برای گزارش‌ها
# MANAGER_PHONE = "989941135190"  # شماره مدیر برای گزارش‌ها
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = 'quick.k1399@gmail.com'
EMAIL_HOST_PASSWORD = 'aaca wuya xuyq assb'
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
