"""
Celery configuration for PX360 project.
"""
import os

from celery import Celery
from celery.schedules import crontab

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

app = Celery('px360')

# Using a string here means the worker doesn't have to serialize
# the configuration object to child processes.
# - namespace='CELERY' means all celery-related configuration keys
#   should have a `CELERY_` prefix.
app.config_from_object('django.conf:settings', namespace='CELERY')

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

# Celery Beat schedule for periodic tasks
app.conf.beat_schedule = {
    # Process unprocessed integration events every 1 minute
    'process-integration-events': {
        'task': 'apps.integrations.tasks.process_pending_events',
        'schedule': crontab(minute='*/1'),
    },
    # Check for overdue complaints every 15 minutes
    'check-overdue-complaints': {
        'task': 'apps.complaints.tasks.check_overdue_complaints',
        'schedule': crontab(minute='*/15'),
    },
    # Check for overdue actions every 15 minutes
    'check-overdue-actions': {
        'task': 'apps.px_action_center.tasks.check_overdue_actions',
        'schedule': crontab(minute='*/15'),
    },
    # Send SLA reminders every hour
    'send-sla-reminders': {
        'task': 'apps.px_action_center.tasks.send_sla_reminders',
        'schedule': crontab(minute=0),  # Every hour at minute 0
    },
    # Calculate daily KPIs at 1 AM
    'calculate-daily-kpis': {
        'task': 'apps.analytics.tasks.calculate_daily_kpis',
        'schedule': crontab(hour=1, minute=0),
    },
    # Calculate physician monthly ratings on the 1st of each month at 2 AM
    'calculate-physician-ratings': {
        'task': 'apps.physicians.tasks.calculate_monthly_ratings',
        'schedule': crontab(hour=2, minute=0, day_of_month=1),
    },
}


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