# -*- coding: utf-8 -*-
"""
Django settings for Adtlas DAI Management System.

This file contains all the configuration settings for the Adtlas project.
The project is designed for Dynamic Ad Insertion (DAI) management in broadcast television.

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

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

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

from pathlib import Path 
from python_decouple import config, Csv
from django.utils.translation import gettext_lazy as _

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

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

# SECURITY WARNING: keep the secret key used in production secret! 
SECRET_KEY = config('SECRET_KEY', default="django-insecure-x+fk6m*$@q4c+3g5ta*$89_stqgegxxlmt42fe5pt$wb)m11-h", cast=str)

# SECURITY WARNING: don"t run with debug turned on in production!
DEBUG = config("DEBUG", default=False, cast=bool)

# Allowed hosts for the application
ALLOWED_HOSTS = config('ALLOWED_HOSTS', default='localhost,127.0.0.1,0.0.0.0,173.212.199.208,_', cast=Csv())

# ==============================================================================
# APPLICATION DEFINITION
# ==============================================================================

# Django built-in applications
DJANGO_APPS = [
    "django.contrib.admin",
    "django.contrib.auth", # Core authentication framework and its default models.
    "django.contrib.contenttypes", # Django content type system (allows permissions to be associated with models).
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "django.contrib.sites",
]

# Third-party applications
THIRD_PARTY_APPS = [
    "rest_framework",
    "corsheaders",
    "django_filters",
    "django_extensions",
    "django_celery_beat",
    "django_celery_results",
]

# Local applications (Adtlas modules)
LOCAL_APPS = [
    "apps.core",
    "apps.accounts",
    "apps.authentication",
    "apps.campaigns",
    "apps.advertisers",
    "apps.channels",
    "apps.playlists",
    "apps.analytics",
    "apps.vast",
]

# Application definition
# All installed applications
INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS

# ==============================================================================
# MIDDLEWARE CONFIGURATION
# ==============================================================================

DJANGO_MIDDLEWARE = [ 
    "corsheaders.middleware.CorsMiddleware", # CORS middleware (should be as high as possible)
    "django.middleware.security.SecurityMiddleware", # Security middleware
    "django.contrib.sessions.middleware.SessionMiddleware", # Manages sessions across requests
    "django.middleware.common.CommonMiddleware", # Common middleware
    "django.middleware.csrf.CsrfViewMiddleware", # CSRF protection middleware
    "django.contrib.auth.middleware.AuthenticationMiddleware", # Associates users with requests using sessions.
    "django.contrib.messages.middleware.MessageMiddleware", # Messages middleware
    "django.middleware.clickjacking.XFrameOptionsMiddleware", # Clickjacking protection middleware
    ]

LOCAL_MIDDLEWARE = [ 
    'django_session_timeout.middleware.SessionTimeoutMiddleware',
]

MIDDLEWARE = DJANGO_MIDDLEWARE + LOCAL_MIDDLEWARE

# ==============================================================================
# URL CONFIGURATION
# ==============================================================================

ROOT_URLCONF = 'core.urls'

# ==============================================================================
# TEMPLATE CONFIGURATION
# ==============================================================================

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [BASE_DIR / "templates"],  # Global templates directory
        "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",
                "django.template.context_processors.media",
                "django.template.context_processors.static",
            ],
        },
    },
]

# ==============================================================================
# WSGI CONFIGURATION
# ==============================================================================

WSGI_APPLICATION = 'core.wsgi.application'

# ==============================================================================
# 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 {},
    #     }
    # }
# ==============================================================================
# DATABASE CONFIGURATION - POSTGRESQL
# ==============================================================================
# Updated to use PostgreSQL for better performance, ACID compliance,
# and advanced features like JSON fields, full-text search, and complex queries

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.postgresql",
        "NAME": config("DB_NAME", default="adtlas_db"),
        "USER": config("DB_USER", default="adtlas_user"),
        "PASSWORD": config("DB_PASSWORD", default="adtlas_password"),
        "HOST": config("DB_HOST", default="localhost"),
        "PORT": config("DB_PORT", default="5432", cast=int),
        "CONN_MAX_AGE": config("DB_CONN_MAX_AGE", default=60, cast=int),
        "OPTIONS": {
            "sslmode": config("DB_SSLMODE", default="prefer"),
            "connect_timeout": 10,
        },
        "TEST": {
            "NAME": "test_adtlas_db",
        }
    }
}

# ==============================================================================
# PASSWORD VALIDATION
# ==============================================================================
# Password validation
# https://docs.djangoproject.com/en/5.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
    },
    {
        "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
        "OPTIONS": {
            "min_length": 8,
        }
    },
    {
        "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
    },
    {
        "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
    },
]

# ==============================================================================
# STATIC FILES CONFIGURATION
# ==============================================================================
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.2/howto/static-files/

STATIC_URL = "/static/"
STATIC_ROOT = BASE_DIR / "staticfiles" # For production
STATICFILES_DIRS = [
    BASE_DIR / "static",  # Global static files directory
]
# STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

# ==============================================================================
# MEDIA FILES CONFIGURATION
# ==============================================================================
# Media files (User uploaded files)

MEDIA_URL = "/media/"
MEDIA_ROOT = BASE_DIR / "media"

# ==============================================================================
# DEFAULT PRIMARY KEY FIELD TYPE
# ==============================================================================
# Default primary key field type
# https://docs.djangoproject.com/en/5.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

# ==============================================================================
# Custom User Model
# ==============================================================================
# # Custom user model
AUTH_USER_MODEL = "accounts.User"

LOGIN_URL = "/auth/login/"
LOGIN_REDIRECT_URL = "/dashboard/"
LOGOUT_REDIRECT_URL = "/auth/login/"
# 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:8090,http://173.212.199.208:8002,https://173.212.199.208:8090,https://173.212.199.208:8002", 
    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,
    "handlers": {
        "console": {
            "level": "INFO",
            "class": "logging.StreamHandler",
        },
    },
    "root": {
        "handlers": ["console"],
        "level": "INFO",
    },
}

# 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/')
# Additional CSRF settings for reverse proxy
CSRF_USE_SESSIONS = False
CSRF_COOKIE_HTTPONLY = False  # Allow JavaScript access to CSRF token if needed
CSRF_COOKIE_SAMESITE = 'Lax'
CSRF_COOKIE_SECURE = False  # Set to True in production with HTTPS

# Trust proxy headers for CSRF
USE_X_FORWARDED_HOST = True
USE_X_FORWARDED_PORT = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

# Ensure logs directory exists
import os
LOGS_DIR = BASE_DIR / 'logs'
os.makedirs(LOGS_DIR, exist_ok=True)

# Enhanced logging configuration
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': {
        'console': {
            'level': 'INFO',
            'class': 'logging.StreamHandler',
            'formatter': 'simple',
        },
    },
    'root': {
        'handlers': ['console'],
        'level': 'INFO',
    },
    'loggers': {
        'django': {
            'handlers': ['console'],
            'level': 'INFO',
            'propagate': False,
        },
    },
}
