"""
Django settings for Stream Processor project.

This module contains all configuration settings for the Django application,
including database configuration, security settings, installed apps,
middleware configuration, and third-party service settings.

The settings are designed to work with python-decouple for environment
variable management, allowing for different configurations across
development, staging, and production environments.
"""

import os
from pathlib import Path
from decouple import config, Csv

# Build paths inside the project like this: BASE_DIR / 'subdir'.
# This is the root directory of the Django project
BASE_DIR = Path(__file__).resolve().parent.parent

# Create logs directory if it doesn't exist
# Ensures the logging directory is available
logs_dir = BASE_DIR / 'logs'
try:
    logs_dir.mkdir(exist_ok=True)
except PermissionError:
    # In Docker, use /app/logs instead
    logs_dir = Path('/app/logs')
    logs_dir.mkdir(exist_ok=True)

# SECURITY WARNING: keep the secret key used in production secret!
# The secret key is used for cryptographic signing and should be unique per installation
SECRET_KEY = config('SECRET_KEY', default='django-insecure-change-this-in-production')

# SECURITY WARNING: don't run with debug turned on in production!
# Debug mode provides detailed error pages and should only be enabled in development
DEBUG = config('DEBUG', default=False, cast=bool)

# Allowed hosts for the Django application
# This list defines which hostnames/IPs can serve the application
ALLOWED_HOSTS = config('ALLOWED_HOSTS', default='localhost,127.0.0.1', cast=Csv())

# Application definition
# List of installed Django applications in order of priority
INSTALLED_APPS = [
    # Django built-in applications
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    
    # Third-party apps
    'rest_framework',
    'corsheaders',
    'django_filters',
    'drf_spectacular',
    
    # Local apps 
    'apps.core',  
    'apps.authentication',  
    'apps.streams',              # Stream management and processing
    'apps.jingles',              # Jingle detection and ad break management
    'apps.notifications',        # Telegram and email notifications
    'apps.monitoring',           # System monitoring and dashboard
]

# Middleware configuration
# Middleware processes requests and responses in order
MIDDLEWARE = [
    # Security middleware for various security headers
    'django.middleware.security.SecurityMiddleware',
    # WhiteNoise for serving static files in production
    'whitenoise.middleware.WhiteNoiseMiddleware',
    # Session middleware for handling user sessions
    'django.contrib.sessions.middleware.SessionMiddleware',
    # CORS middleware for handling cross-origin requests
    'corsheaders.middleware.CorsMiddleware',
    # Common middleware for common request/response processing
    'django.middleware.common.CommonMiddleware',
    # CSRF protection middleware
    'django.middleware.csrf.CsrfViewMiddleware',
    # Authentication middleware for user authentication
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    # Message middleware for handling messages framework
    'django.contrib.messages.middleware.MessageMiddleware',
    # Clickjacking protection middleware
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

# Root URL configuration module
# Points to the main URL configuration file
ROOT_URLCONF = 'core.urls'

# Template configuration
# Defines how Django finds and processes templates
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / 'templates'],  # Global template directory
        'APP_DIRS': True,  # Look for templates in each app's templates directory
        'OPTIONS': {
            'context_processors': [
                # Built-in 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',
                # Custom context processors
                'apps.core.context_processors.settings_context',
            ],
        },
    },
]

# WSGI application configuration
# Points to the WSGI application callable
WSGI_APPLICATION = 'core.wsgi.application'

# ASGI application configuration
# Points to the ASGI application callable
ASGI_APPLICATION = 'core.asgi.application'

# Database configuration
# Uses PostgreSQL as the primary database, SQLite for testing
if config('USE_SQLITE', default=False, cast=bool):
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': BASE_DIR / 'db.sqlite3',
        }
    }
else:
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.postgresql',
            'NAME': config('DB_NAME', default='stream_db'),
            'USER': config('DB_USER', default='postgres'),
            'PASSWORD': config('DB_PASSWORD', default='postgres'),
            'HOST': config('DB_HOST', default='localhost'),
            'PORT': config('DB_PORT', default='5432'),
            'CONN_MAX_AGE': config('DB_CONN_MAX_AGE', default=600, cast=int),  # Connection pooling
            'CONN_HEALTH_CHECKS': config('DB_CONN_HEALTH_CHECKS', default=True, cast=bool),
            'OPTIONS': {
                # Connection options for better performance and reliability
                'connect_timeout': 60,
                'options': '-c default_transaction_isolation=serializable',
                # Performance optimizations
                'sslmode': config('DB_SSL_MODE', default='prefer'),
                'application_name': 'stream_processor',
            }
        }
    }

# Password validation
# Ensures strong password requirements for user accounts
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 settings
# Configures language and timezone settings
LANGUAGE_CODE = 'en-us'
TIME_ZONE = config('TIME_ZONE', default='UTC')
USE_I18N = True
USE_TZ = True

# Static files configuration (CSS, JavaScript, Images)
# Defines how static files are collected and served
STATIC_URL = config('STATIC_URL', default='/static/')
STATIC_ROOT = config('STATIC_ROOT', default=BASE_DIR / 'staticfiles')
STATICFILES_DIRS = [BASE_DIR / 'static']

# Static files storage configuration
# Uses WhiteNoise for static file compression and caching
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

# Media files configuration
# Defines where user-uploaded files are stored and served
MEDIA_URL = config('MEDIA_URL', default='/media/')
MEDIA_ROOT = config('MEDIA_ROOT', default=BASE_DIR / 'media')

# Default primary key field type
# Specifies the default primary key type for models
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

# Django REST Framework configuration
# Configures the API framework settings
REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 20,
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.TokenAuthentication',
    ],
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated',
    ],
    'DEFAULT_RENDERER_CLASSES': [
        'rest_framework.renderers.JSONRenderer',
        'rest_framework.renderers.BrowsableAPIRenderer',
    ],
    'DEFAULT_THROTTLE_CLASSES': [
        'rest_framework.throttling.AnonRateThrottle',
        'rest_framework.throttling.UserRateThrottle'
    ],
    'DEFAULT_THROTTLE_RATES': {
        'anon': '100/hour',
        'user': '1000/hour',
        'stream_control': '30/minute',
        'detection_api': '500/hour',
        'notification_api': '200/hour'
    },
    'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema',
}

# CORS configuration
# Configures Cross-Origin Resource Sharing for API access
CORS_ALLOWED_ORIGINS = config('CORS_ALLOWED_ORIGINS', default='', cast=Csv())
CORS_ALLOW_CREDENTIALS = True

# Celery configuration
# Background task processing configuration
CELERY_BROKER_URL = config('CELERY_BROKER_URL', default='redis://localhost:6379/0')
CELERY_RESULT_BACKEND = config('CELERY_RESULT_BACKEND', default='redis://localhost:6379/0')
CELERY_ACCEPT_CONTENT = ['json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TIMEZONE = TIME_ZONE
CELERY_ENABLE_UTC = True

# Cache configuration
# Redis-based caching for improved performance
CACHES = {
    'default': {
        'BACKEND': 'django_redis.cache.RedisCache',
        'LOCATION': config('REDIS_URL', default='redis://localhost:6379/1'),
        'OPTIONS': {
            'CLIENT_CLASS': 'django_redis.client.DefaultClient',
            'CONNECTION_POOL_KWARGS': {
                'max_connections': config('REDIS_MAX_CONNECTIONS', default=50, cast=int),
                'retry_on_timeout': True,
            },
            'SERIALIZER': 'django_redis.serializers.json.JSONSerializer',
            'COMPRESSOR': 'django_redis.compressors.zlib.ZlibCompressor',
        },
        'KEY_PREFIX': 'stream_processor',
        'TIMEOUT': config('CACHE_DEFAULT_TIMEOUT', default=300, cast=int),  # 5 minutes
    }
}

# Session configuration to use Redis
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
SESSION_CACHE_ALIAS = 'default'

# Performance profiling configuration
PERFORMANCE_PROFILING_ENABLED = config('PERFORMANCE_PROFILING_ENABLED', default=False, cast=bool)

# Celery Beat configuration for periodic tasks
CELERY_BEAT_SCHEDULE = {
    'stream-health-check': {
        'task': 'apps.streams.tasks.check_stream_health',
        'schedule': 30.0,  # Every 30 seconds
    },
    'cleanup-old-segments': {
        'task': 'apps.streams.tasks.cleanup_old_segments',
        'schedule': 86400.0,  # Every 24 hours
    },
    'process-ad-breaks': {
        'task': 'apps.jingles.tasks.process_pending_ad_breaks',
        'schedule': 60.0,  # Every minute
    },
    'collect-system-metrics': {
        'task': 'apps.monitoring.tasks.collect_system_metrics',
        'schedule': 60.0,  # Every minute
    },
    'collect-app-metrics': {
        'task': 'apps.monitoring.tasks.collect_app_metrics',
        'schedule': 120.0,  # Every 2 minutes
    },
    'generate-performance-report': {
        'task': 'apps.monitoring.tasks.generate_performance_report',
        'schedule': 1800.0,  # Every 30 minutes
    },
    'monitor-resource-usage': {
        'task': 'apps.monitoring.tasks.monitor_resource_usage',
        'schedule': 300.0,  # Every 5 minutes
    },
    'cleanup-metrics-cache': {
        'task': 'apps.monitoring.tasks.cleanup_metrics_cache',
        'schedule': 3600.0,  # Every hour
    },
    'check-external-services': {
        'task': 'apps.monitoring.tasks.check_external_services_health',
        'schedule': 600.0,  # Every 10 minutes
    },
    'create-backup': {
        'task': 'apps.monitoring.tasks.create_backup',
        'schedule': 86400.0,  # Daily backup
    },
    'cleanup-backups': {
        'task': 'apps.monitoring.tasks.cleanup_backups',
        'schedule': 604800.0,  # Weekly cleanup
    },
}

# Stream processing configuration
# Settings specific to stream capture and processing
STREAM_CONFIG = {
    'OUTPUT_DIR': config('OUTPUT_DIR', default='/app/media/streams'),
    'SEGMENT_DURATION': config('SEGMENT_DURATION', default=6, cast=int),
    'MAX_TS_FILE_NUMBER': config('MAX_TS_FILE_NUMBER', default=10, cast=int),
    'MAX_CAPTURE_RETRIES': config('MAX_CAPTURE_RETRIES', default=5, cast=int),
    'CAPTURE_RETRY_INTERVAL': config('CAPTURE_RETRY_INTERVAL', default=10, cast=int),
    'EXIT_ON_FAILURE': config('EXIT_ON_FAILURE', default=True, cast=bool),
}

# Video encoding configuration
# FFmpeg encoding parameters for stream processing
VIDEO_CONFIG = {
    'RESOLUTION': config('RESOLUTION', default='1280x720'),
    'ASPECT_RATIO': config('ASPECT_RATIO', default='16:9'),
    'FPS': config('FPS', default=25, cast=int),
    'MIN_BITRATE': config('MIN_BITRATE', default='2000k'),
    'MAX_BITRATE': config('MAX_BITRATE', default='4000k'),
}

# Audio encoding configuration
# Audio processing parameters for stream encoding
AUDIO_CONFIG = {
    'BITRATE': config('AUDIO_BITRATE', default='128k'),
    'SAMPLE_RATE': config('AUDIO_SAMPLE_RATE', default=48000, cast=int),
    'CHANNELS': config('AUDIO_CHANNELS', default=2, cast=int),
}

# Telegram bot configuration
# Settings for Telegram notifications
TELEGRAM_CONFIG = {
    'BOT_TOKEN': config('TELEGRAM_BOT_TOKEN', default=''),
    'CHAT_ID': config('TELEGRAM_CHAT_ID', default=''),
    'ENABLED': bool(config('TELEGRAM_BOT_TOKEN', default='')),
}

# Jingle detection configuration
# Settings for ad break detection using jingles
JINGLE_CONFIG = {
    'USE_JINGLES': config('USE_JINGLES', default=True, cast=bool),
    'SIMILARITY_THRESHOLD': config('JINGLE_SIMILARITY_THRESHOLD', default=0.1, cast=float),
    'MIN_AD_BREAK_DURATION': config('MIN_AD_BREAK_DURATION', default=3, cast=int),
    'MAX_AD_BREAK_DURATION': config('MAX_AD_BREAK_DURATION', default=330, cast=int),
}

# External API configuration
# Settings for external service integrations
EXTERNAL_APIS = {
    'DAI_API_URL': config('DAI_API_URL', default=''),
}

# Logging configuration
# Comprehensive logging setup for debugging and monitoring
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': config('LOG_LEVEL', default='INFO'),
            'propagate': False,
        },
        'core': {
            'handlers': ['console'],
            'level': 'INFO',
            'propagate': False,
        },
        'celery': {
            'handlers': ['console'],
            'level': 'INFO',
            'propagate': False,
        },
    },
}

# Authentication settings
# Configure login/logout behavior
LOGIN_URL = '/accounts/login/'
LOGIN_REDIRECT_URL = '/'
LOGOUT_REDIRECT_URL = '/accounts/login/'

# Security settings for production
# Additional security configurations for deployment
if not DEBUG:
    # HTTPS settings
    SECURE_SSL_REDIRECT = config('SECURE_SSL_REDIRECT', default=True, cast=bool)
    SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
    
    # Cookie security
    SESSION_COOKIE_SECURE = config('SESSION_COOKIE_SECURE', default=True, cast=bool)
    CSRF_COOKIE_SECURE = config('CSRF_COOKIE_SECURE', default=True, cast=bool)
    
    # Security headers
    SECURE_BROWSER_XSS_FILTER = True
    SECURE_CONTENT_TYPE_NOSNIFF = True
    X_FRAME_OPTIONS = 'DENY'

# DRF Spectacular configuration for OpenAPI documentation
SPECTACULAR_SETTINGS = {
    'TITLE': 'Stream Processing API',
    'DESCRIPTION': 'Comprehensive API for HLS stream capture, jingle detection, and notification management',
    'VERSION': '1.0.0',
    'SERVE_INCLUDE_SCHEMA': False,
    'SCHEMA_PATH_PREFIX': '/api/v1/',
    'DEFAULT_GENERATOR_CLASS': 'drf_spectacular.generators.SchemaGenerator',
    'SERVE_PERMISSIONS': ['rest_framework.permissions.IsAuthenticated'],
    'SERVE_AUTHENTICATION': [
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.TokenAuthentication',
    ],
    'SWAGGER_UI_SETTINGS': {
        'deepLinking': True,
        'persistAuthorization': True,
        'displayOperationId': True,
        'filter': True,
    },
    'COMPONENT_SPLIT_REQUEST': True,
    'SORT_OPERATIONS': False,
    'TAGS': [
        {'name': 'Channels', 'description': 'Stream channel management'},
        {'name': 'Sessions', 'description': 'Stream session monitoring'},
        {'name': 'Configurations', 'description': 'Video and audio encoding settings'},
        {'name': 'Jingles', 'description': 'Jingle template and detection management'},
        {'name': 'Ad Breaks', 'description': 'Advertisement break tracking'},
        {'name': 'Notifications', 'description': 'Multi-channel notification system'},
        {'name': 'Monitoring', 'description': 'System health and metrics'},
    ],
}
