
from celery import shared_task
from django.core.management import call_command
import logging

logger = logging.getLogger(__name__)

@shared_task
def process_customer_service_statuses():
    """
    Celery task to process customer service statuses and send notifications
    This should be scheduled to run daily
    """
    try:
        logger.info("Starting automated service status processing")
        call_command('process_service_statuses')
        logger.info("Completed automated service status processing")
        return "Service status processing completed successfully"
    except Exception as e:
        logger.error(f"Error in automated service status processing: {str(e)}")
        return f"Service status processing failed: {str(e)}"

@shared_task
def send_daily_reminders():
    """
    Send daily service expiry reminders (3 days before expiry)
    """
    try:
        from django.utils import timezone
        from datetime import timedelta
        from customers.models import Customer
        from customers.services import CustomerNotificationService
        from billing.models import ServicePeriod
        
        now = timezone.now()
        reminder_date = now + timedelta(days=3)
        
        # Find service periods expiring in 3 days
        expiring_periods = ServicePeriod.objects.filter(
            status='active',
            service_end__date=reminder_date.date()
        ).select_related('customer', 'service')
        
        sent_count = 0
        for period in expiring_periods:
            try:
                CustomerNotificationService.send_service_expiry_reminder(
                    period.customer, 3
                )
                sent_count += 1
            except Exception as e:
                logger.error(f"Failed to send reminder to {period.customer.customer_id}: {str(e)}")
        
        logger.info(f"Sent {sent_count} service expiry reminders")
        return f"Sent {sent_count} reminders successfully"
        
    except Exception as e:
        logger.error(f"Error in daily reminders task: {str(e)}")
        return f"Daily reminders task failed: {str(e)}"
</shared_task>
