from celery import Celery
from celery.schedules import crontab
from app.config import Config
from app.config import setup_logging
import os


# Set up logging first
setup_logging()

# Configure Celery with explicit Redis settings
celery = Celery(
    'app',
    broker='redis://127.0.0.1:6379/0',
    backend='redis://127.0.0.1:6379/0',
    include=['app.tasks']  # Explicitly include tasks module
)

# Configure Celery settings
celery.conf.update(
    task_serializer='json',
    accept_content=['json'],
    result_serializer='json',
    timezone='UTC',
    enable_utc=True,
    worker_max_tasks_per_child=200,  # Restart worker after 200 tasks
    worker_prefetch_multiplier=1,    # Process one task at a time
    task_acks_late=True,            # Acknowledge task after completion
    task_reject_on_worker_lost=True, # Reject task if worker dies
    broker_connection_retry=True,
    broker_connection_max_retries=10
)

# Configure periodic tasks
celery.conf.beat_schedule = {
      # 'check-scheduled-campaigns': {
    #     'task': 'app.utils.email_campaign.check_and_send_scheduled_campaigns',
    #     'schedule': 60.0,  # Run every minute
    # },
    # 'scan-email-replies': {
    #     'task': 'app.utils.email_reply_scanner.scan_email_replies',
    #     'schedule': 300.0,  # Run every 5 minutes
    # }
}
