# -*- coding: utf-8 -*-
"""
Celery configuration for Adtlas DAI Management System.

This module configures Celery for handling background tasks such as:
- VAST call processing
- Ad encoding operations
- Analytics data processing
- Report generation
- File transfers
- Notification sending

Celery is used for:
1. Asynchronous task execution
2. Periodic task scheduling
3. Task result storage
4. Task monitoring and management

For more information on Celery configuration, see:
https://docs.celeryproject.org/en/stable/django/first-steps-with-django.html
"""

from __future__ import absolute_import, unicode_literals

import os
from celery import Celery
from django.conf import settings

# Set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings')

# Create a new Celery app instance
app = Celery('adtlas')

# Using a string here means the worker doesn't have to serialize
# the configuration object to child processes.
app.config_from_object('django.conf:settings', namespace='CELERY')

# Load task modules from all registered Django apps.
app.autodiscover_tasks()

# Optional configuration, see the application user guide.
app.conf.update(
    task_track_started=True,

    # Task serialization
    task_serializer='json',
    accept_content=['json'],
    result_serializer='json',
    
    # Broker connection settings
    broker_connection_retry_on_startup=True,  # Fix for Celery 6.0+ deprecation warning
    
    result_backend='redis://redis:6379/0',
    timezone='UTC',
    enable_utc=True,

    # Task execution settings
    task_always_eager=False,
    task_eager_propagates=True,
    task_ignore_result=False,
    task_store_eager_result=True,
    
    # Worker settings
    worker_prefetch_multiplier=1,
    worker_max_tasks_per_child=1000,
    
    # Result backend settings
    result_expires=3600,  # 1 hour
    result_backend_transport_options={
        'master_name': 'mymaster',
    },

)

@app.task(bind=True)
def debug_task(self):
    """
    Debug task for testing Celery configuration.
    
    This task can be used to verify that Celery is working correctly.
    It prints the request information and returns a success message.
    
    Returns:
        str: Debug information about the task request
    """
    print(f'Request: {self.request!r}')
    return f'Debug task executed successfully. Request ID: {self.request.id}'


@app.task
def health_check():
    """
    Health check task for monitoring Celery workers.
    
    This task can be used by monitoring systems to verify that
    Celery workers are responsive and functioning correctly.
    
    Returns:
        dict: Health status information
    """
    return {
        'status': 'healthy',
        'service': 'Adtlas Celery Worker',
        'timestamp': app.now().isoformat()
    }