"""
Django settings for media_analyzer project.

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

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

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


# 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 = "django-insecure-n=jmw6r)102f0mytr7m1q5qwk^v$fd8gyokqpglsd&rl$d(^0="

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = os.getenv('DEBUG', 'True').lower() in ('true', '1', 'yes')

ALLOWED_HOSTS = os.getenv('ALLOWED_HOSTS', 'localhost,127.0.0.1').split(',')


# Application definition

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "corsheaders",  # For CORS
    "channels",  # For WebSocket
    "streaming",
    "ai_processing",
    "effects",
    "api",
]

MIDDLEWARE = [
    "corsheaders.middleware.CorsMiddleware",  # Add this first
    "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 = "media_analyzer.urls"

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [],
        "APP_DIRS": True,
        "OPTIONS": {
            "context_processors": [
                "django.template.context_processors.request",
                "django.contrib.auth.context_processors.auth",
                "django.contrib.messages.context_processors.messages",
            ],
        },
    },
]

WSGI_APPLICATION = "media_analyzer.wsgi.application"
ASGI_APPLICATION = "media_analyzer.asgi.application"

# Redis configuration
REDIS_HOST = os.getenv('REDIS_HOST', '127.0.0.1')
REDIS_PORT = int(os.getenv('REDIS_PORT', '6379'))

# Channels configuration
CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "channels_redis.core.RedisChannelLayer",
        "CONFIG": {
            "hosts": [(REDIS_HOST, REDIS_PORT)],
        },
    },
}

# Celery configuration
CELERY_BROKER_URL = f'redis://{REDIS_HOST}:{REDIS_PORT}/0'
CELERY_RESULT_BACKEND = f'redis://{REDIS_HOST}:{REDIS_PORT}/0'
CELERY_ACCEPT_CONTENT = ['json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TIMEZONE = 'UTC'

# Celery queue routing
CELERY_TASK_ROUTES = {
    'ai_processing.tasks.analyze_visual_properties': {'queue': 'visual_analysis'},
    'ai_processing.tasks.reload_analysis_config': {'queue': 'config_management'},
    'ai_processing.event_tasks.process_segment_from_event': {'queue': 'logo_detection'},
    'ai_processing.event_tasks.start_event_processor': {'queue': 'default'},
}

# Define queues with different priorities
CELERY_TASK_DEFAULT_QUEUE = 'default'
CELERY_TASK_QUEUES = {
    'default': {
        'routing_key': 'default',
    },
    'logo_detection': {
        'routing_key': 'logo_detection',
    },
    'visual_analysis': {
        'routing_key': 'visual_analysis',
    },
    'config_management': {
        'routing_key': 'config_management',
    },
}


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

import os

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.postgresql",
        "NAME": os.getenv("DB_NAME", "media_analyzer"),
        "USER": os.getenv("DB_USER", "media_user"), 
        "PASSWORD": os.getenv("DB_PASSWORD", "media_pass"),
        "HOST": os.getenv("DB_HOST", "localhost"),
        "PORT": os.getenv("DB_PORT", "5432"),
    }
}


# 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",
    },
    {
        "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
    },
    {
        "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
    },
]


# Internationalization
# https://docs.djangoproject.com/en/5.2/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.2/howto/static-files/

STATIC_URL = "/static/"
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

# Media files
MEDIA_URL = '/media/'
MEDIA_ROOT = os.getenv('MEDIA_ROOT', BASE_DIR / 'media')

# Streaming settings
RTMP_PORT = int(os.getenv('RTMP_PORT', 1935))
HLS_BASE_URL = os.getenv('HLS_BASE_URL', 'http://localhost:8000')
HLS_ENDPOINT_PATH = os.getenv('HLS_ENDPOINT_PATH', '/streaming/hls/')  # For Django dev mode
# When using GCS, this would be: 'https://storage.googleapis.com/bucket-name/'

# CORS settings
CORS_ALLOWED_ORIGINS = [
    "http://localhost:4200",  # Angular dev server
    "http://127.0.0.1:4200",
]

# For development - allow all origins (comment out for production)
CORS_ALLOW_ALL_ORIGINS = True

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

DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

# =============================================================================
# GCP and Cloud Services Configuration
# =============================================================================

# AI Processing Configuration
USE_CLOUD_VISION = os.getenv('USE_CLOUD_VISION', 'false').lower() == 'true'
USE_LOCAL_CLIP = not USE_CLOUD_VISION

# Storage Configuration  
USE_CLOUD_STORAGE = os.getenv('USE_CLOUD_STORAGE', 'false').lower() == 'true'
GCP_BUCKET_NAME = os.getenv('GCP_BUCKET_NAME', 'media-analyzer-segments')
GCP_PROJECT_ID = os.getenv('GCP_PROJECT_ID')

# GCS Storage Settings (when USE_CLOUD_STORAGE=true)
if USE_CLOUD_STORAGE:
    DEFAULT_FILE_STORAGE = 'storages.backends.gcloud.GoogleCloudStorage'
    GS_BUCKET_NAME = GCP_BUCKET_NAME
    GS_PROJECT_ID = GCP_PROJECT_ID
    GS_AUTO_CREATE_BUCKET = True
    GS_AUTO_CREATE_ACL = 'publicRead'  # For HLS streaming access
    GS_DEFAULT_ACL = 'publicRead'
    
    # Update media URL to use GCS
    MEDIA_URL = f'https://storage.googleapis.com/{GCP_BUCKET_NAME}/'
    
    # HLS endpoint for GCS
    HLS_BASE_URL = f'https://storage.googleapis.com/{GCP_BUCKET_NAME}'
else:
    # Local storage (default)
    DEFAULT_FILE_STORAGE = 'django.core.files.storage.FileSystemStorage'

# GCP Credentials
GOOGLE_APPLICATION_CREDENTIALS = os.getenv('GOOGLE_APPLICATION_CREDENTIALS')

# AI Analysis Strategy
if USE_CLOUD_VISION:
    AI_ANALYSIS_BACKEND = 'ai_processing.backends.CloudVisionBackend'
else:
    AI_ANALYSIS_BACKEND = 'ai_processing.backends.LocalClipBackend'

# Logo Detection Configuration
LOGO_DETECTION_CONFIG = {
    'confidence_threshold': float(os.getenv('LOGO_CONFIDENCE_THRESHOLD', '0.6')),
    'enabled_brands': os.getenv('ENABLED_BRANDS', 'Apple,Google,Nike,Coca-Cola,McDonald,Amazon').split(','),
    'use_cloud_vision': USE_CLOUD_VISION,
}

# Event Source Configuration
SEGMENT_EVENT_SOURCE = os.getenv('SEGMENT_EVENT_SOURCE', 'filewatcher').lower()
FILE_WATCHER_POLL_INTERVAL = float(os.getenv('FILE_WATCHER_POLL_INTERVAL', '1.0'))
WEBHOOK_PORT = int(os.getenv('WEBHOOK_PORT', '8001'))

# =============================================================================
# Kubernetes and Container Configuration
# =============================================================================

# Update service URLs for K8s deployment
if os.getenv('KUBERNETES_SERVICE_HOST'):
    # Running in Kubernetes
    REDIS_HOST = os.getenv('REDIS_SERVICE_HOST', 'redis-service')
    REDIS_PORT = int(os.getenv('REDIS_SERVICE_PORT', '6379'))
    
    # Update Celery broker for K8s
    CELERY_BROKER_URL = f'redis://{REDIS_HOST}:{REDIS_PORT}/0'
    CELERY_RESULT_BACKEND = f'redis://{REDIS_HOST}:{REDIS_PORT}/0'
    
    # Update channels for K8s
    CHANNEL_LAYERS["default"]["CONFIG"]["hosts"] = [(REDIS_HOST, REDIS_PORT)]
    
    # Update database host for K8s
    DATABASES["default"]["HOST"] = os.getenv("DB_HOST", "postgres-service")
    
    # Update CORS for K8s ingress
    CORS_ALLOWED_ORIGINS.extend([
        f"http://{os.getenv('INGRESS_HOST', 'localhost')}",
        f"https://{os.getenv('INGRESS_HOST', 'localhost')}",
    ])

# =============================================================================
# Logging Configuration
# =============================================================================

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': '{levelname} {asctime} {module} {process:d} {thread:d} {message}',
            'style': '{',
        },
    },
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
            'formatter': 'verbose',
        },
    },
    'loggers': {
        'streaming.file_watcher': {
            'handlers': ['console'],
            'level': 'INFO',  # Changed from DEBUG
            'propagate': True,
        },
        'streaming.event_sources': {
            'handlers': ['console'],
            'level': 'INFO',
            'propagate': True,
        },
        'streaming.event_source_manager': {
            'handlers': ['console'],
            'level': 'INFO',
            'propagate': True,
        },
        'ai_processing': {
            'handlers': ['console'],
            'level': 'INFO',
            'propagate': True,
        },
    },
    'root': {
        'handlers': ['console'],
        'level': 'INFO',
    },
}

# =============================================================================
# Production Security Settings
# =============================================================================

# Update secret key from environment in production
if not DEBUG:
    SECRET_KEY = os.getenv('DJANGO_SECRET_KEY', SECRET_KEY)
    
    # Ensure security settings for production
    SECURE_BROWSER_XSS_FILTER = True
    SECURE_CONTENT_TYPE_NOSNIFF = True
    X_FRAME_OPTIONS = 'DENY'
    
    # Only enable cloud features in production/K8s
    if os.getenv('KUBERNETES_SERVICE_HOST') or os.getenv('USE_CLOUD_SERVICES'):
        USE_CLOUD_VISION = True
        USE_CLOUD_STORAGE = True
