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

# # Check if DATABASE_URL is provided (Docker environment)
# if config("DATABASE_URL", default=None, cast=str):
#     # Database configuration with support for PostgreSQL and MySQL
#     import dj_database_url
#     DATABASES = {
#         "default": dj_database_url.parse(config("DATABASE_URL", default=None, cast=str))
#     }
# else:
    # DATABASES = {
    #     "default": {
    #         "ENGINE": config("DB_ENGINE", default="django.db.backends.sqlite3", cast=str),
    #         "NAME": config("DB_NAME", default=BASE_DIR / "db.sqlite3", cast=str),
    #         "USER": config("DB_USER", default="", cast=str),
    #         "PASSWORD": config("DB_PASSWORD", default="", cast=str),
    #         "HOST": config("DB_HOST", default="", cast=str),
    #         "PORT": config("DB_PORT", default="", cast=str),
    #         "OPTIONS": {
    #             "charset": "utf8mb4",
    #         } if config("DB_ENGINE", default="", cast=str).endswith("mysql") else {},
    #     }
    # }
DATABASES = {
    "default": {
        "ENGINE": config("DB_ENGINE", default="django.db.backends.mysql", cast=str),
        "NAME": config("DB_NAME", default="adtlas_db", cast=str),
        "USER": config("DB_USER", default="adtlas_user", cast=str),
        "PASSWORD": config("DB_PASSWORD", default="adtlas_password", cast=str),
        "HOST": config("DB_HOST", default="db", cast=str),
        "PORT": config("DB_PORT", default="3306", cast=str),
        "OPTIONS": {
            "charset": "utf8mb4",
        } if config("DB_ENGINE", default="mysql", cast=str).endswith("mysql") else {},
    }
}

# Database connection pooling (optional)
if config("DB_CONN_MAX_AGE", default=None):
    DATABASES["default"]["CONN_MAX_AGE"] = config("DB_CONN_MAX_AGE", default=600, cast=int)
 

 
# ==============================================================================
# Custom User Model
# ==============================================================================
# # Custom user model


# LOGIN_URL = "auth:login"
# LOGIN_REDIRECT_URL = "core:dashboard"
# LOGOUT_REDIRECT_URL = "auth:login"

# ==============================================================================
# Site ID for django.contrib.sites
# ==============================================================================

SITE_ID = config("SITE_ID", default=1, cast=int) 

# ==============================================================================
# REST FRAMEWORK CONFIGURATION
# ==============================================================================

# Django REST Framework configuration
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.TokenAuthentication',
    ],
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated',
    ],
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    "PAGE_SIZE": 20,
    "DEFAULT_FILTER_BACKENDS": [
        "django_filters.rest_framework.DjangoFilterBackend",
        "rest_framework.filters.SearchFilter",
        "rest_framework.filters.OrderingFilter",
    ],
    "DEFAULT_RENDERER_CLASSES": [
        "rest_framework.renderers.JSONRenderer",
        "rest_framework.renderers.BrowsableAPIRenderer",
    ],
}

# ==============================================================================
# CORS CONFIGURATION
# ==============================================================================
# CORS settings
CORS_ALLOWED_ORIGINS = config(
    "CORS_ALLOWED_ORIGINS", 
    default="http://localhost:3000,http://127.0.0.1:3000,http://localhost:8080,http://127.0.0.1:8080",  # Vue development server
    cast=Csv()
)
CORS_ALLOW_ALL_ORIGINS = config("CORS_ALLOW_ALL_ORIGINS", default=True, cast=bool)
CORS_ALLOW_CREDENTIALS = config("CORS_ALLOW_CREDENTIALS", default=True, cast=bool)

# ==============================================================================
# CSRF CONFIGURATION
# ==============================================================================

# CSRF trusted origins for cross-origin requests
CSRF_TRUSTED_ORIGINS = config(
    "CSRF_TRUSTED_ORIGINS", 
    default="http://localhost:8000,http://127.0.0.1:8000,http://173.212.199.208:8082", 
    cast=Csv()
) 

# Internationalization
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
USE_THOUSAND_SEPARATOR = True
 
# Session settings
SESSION_EXPIRE_SECONDS = int(config('SESSION_EXPIRE_SECONDS', default='7200'))  # 2 hours
SESSION_EXPIRE_AFTER_LAST_ACTIVITY = True
SESSION_TIMEOUT_REDIRECT = '/auth/login/'

# Celery Configuration
CELERY_BROKER_URL = config('CELERY_BROKER_URL', default='redis://redis:6379/0')
CELERY_RESULT_BACKEND = config('CELERY_RESULT_BACKEND', default='redis://redis:6379/0')
CELERY_ACCEPT_CONTENT = ['json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TIMEZONE = TIME_ZONE



# Logging
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': {
        'file': {
            'level': 'INFO',
            'class': 'logging.FileHandler',
            'filename': BASE_DIR / 'logs' / 'django.log',
            'formatter': 'verbose',
        },
        'console': {
            'level': 'INFO',
            'class': 'logging.StreamHandler',
            'formatter': 'simple',
        },
    },
    'root': {
        'handlers': ['console', 'file'],
        'level': 'INFO',
    },
    'loggers': {
        'django': {
            'handlers': ['console', 'file'],
            'level': 'INFO',
            'propagate': False,
        },
    },
}

# Telegram Bot Configuration
TELEGRAM = {
    'bot_token': config('TELEGRAM_BOT_TOKEN', default=''),
    'channel_name': config('TELEGRAM_CHANNEL_NAME', default='adtlasbot'),
}

# Application URL prefix
APP_URL = config('APP_URL', default='/adtlas/')