from django.db.models.signals import post_save
from django.dispatch import receiver
from stamps.models import Stamp
from .tasks import analyze_user_patterns_task, schedule_user_notifications_for_today
from .services import MLService
import logging

logger = logging.getLogger(__name__)

@receiver(post_save, sender=Stamp)
def on_stamp_created(sender, instance, created, **kwargs):
    """
    Automatic ML analysis when new stamp is created
    """
    if created:
        try:
            # Only process if stamp_function is not 'none'
            if instance.stamp_function != 'none':
                logger.info(f"Processing new stamp for user {instance.user.id}, type: {instance.stamp_function}")
                
                # Analyze patterns in background
                analyze_user_patterns_task.delay(str(instance.user.id))
                
                # Detect anomalies immediately
                ml_service = MLService()
                anomaly = ml_service.detect_anomalies_for_new_stamp(str(instance.user.id), instance)
                
                if anomaly:
                    logger.warning(f"Anomaly detected for user {instance.user.id}: {anomaly}")
                
                # Schedule notifications for this user
                try:
                    schedule_user_notifications_for_today(instance.user.id)
                except Exception as e:
                    logger.warning(f"Could not schedule notifications for user {instance.user.id}: {e}")
                    
        except Exception as e:
            logger.error(f"Error processing stamp creation: {e}")
