"""
Celery configuration for ThrillWiki.

This module initializes the Celery application and configures
task discovery, error handling, and monitoring.
"""

import os
from celery import Celery
from celery.signals import task_failure, task_success
from django.conf import settings

# Set default Django settings module
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.local')

# Create Celery app
app = Celery('thrillwiki')

# Load configuration from Django settings
app.config_from_object('django.conf:settings', namespace='CELERY')

# Auto-discover tasks from all installed apps
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)


@app.task(bind=True, ignore_result=True)
def debug_task(self):
    """Debug task to test Celery configuration."""
    print(f'Request: {self.request!r}')


# Task failure signal handler
@task_failure.connect
def task_failure_handler(sender=None, task_id=None, exception=None, **kwargs):
    """Log task failures for monitoring."""
    import logging
    logger = logging.getLogger('celery.task')
    logger.error(
        f'Task {sender.name} ({task_id}) failed: {exception}',
        exc_info=True,
        extra={'task_id': task_id, 'task_name': sender.name}
    )


# Task success signal handler
@task_success.connect
def task_success_handler(sender=None, result=None, **kwargs):
    """Log task successes for monitoring."""
    import logging
    logger = logging.getLogger('celery.task')
    logger.info(
        f'Task {sender.name} completed successfully',
        extra={'task_name': sender.name, 'result': str(result)[:200]}
    )
