from django.db.models.signals import post_save, pre_save
from django.utils import timezone
from django.dispatch import receiver
from .models import ( 
    CollectionData, Lead, Quote, Invoice, QuoteItem
)
from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver


@receiver(post_save, sender=CollectionData)
def handle_collection_conversion(sender, instance, created, **kwargs):
    if instance.interested and not instance.leads.exists():
        instance.convert_to_lead()

@receiver(pre_save, sender=Lead)
def handle_lead_conversion(sender, instance, **kwargs):
    if instance.is_converted and not instance.converted_date:
        instance.converted_date = timezone.now()


# Quote to Invoice Convert - Automatic

@receiver(post_save, sender=Quote)
def handle_quote_to_invoice(sender, instance, created, **kwargs):
    """
    Automatically create invoice when is_invoice_converted is set to True
    Only creates ONE invoice per quote
    """
    # Process if is_invoice_converted is True (both creation and updates)
    # This handles both automatic conversion on creation and manual conversion on updates
    if instance.is_invoice_converted:
        # Check if invoice already exists for this quote
        existing_invoice = Invoice.objects.filter(quote=instance).first()
        
        if not existing_invoice:
            # Create invoice automatically - only if none exists
            try:
                # Use a flag to prevent infinite recursion
                if not hasattr(instance, '_converting_to_invoice'):
                    instance._converting_to_invoice = True
                    invoice = instance.convert_to_invoice()
                    if invoice:
                        print(f"[SUCCESS] Auto-created invoice {invoice.invoice_number} for quote {instance.quote_number}")
                    delattr(instance, '_converting_to_invoice')
            except Exception as e:
                print(f"[ERROR] Error creating invoice for quote {instance.quote_number}: {e}")
                if hasattr(instance, '_converting_to_invoice'):
                    delattr(instance, '_converting_to_invoice')
        else:
            # Ensure the existing invoice has items from the quote
            if existing_invoice.items.count() == 0:
                try:
                    existing_invoice.ensure_items_from_quote()
                    print(f"[SUCCESS] Updated existing invoice {existing_invoice.invoice_number} with quote items")
                except Exception as e:
                    print(f"[ERROR] Error updating invoice {existing_invoice.invoice_number}: {e}")
            else:
                print(f"[INFO] Invoice already exists for quote {instance.quote_number}: {existing_invoice.invoice_number}")




@receiver([post_save, post_delete], sender=QuoteItem)
def update_quote_total_and_pdf(sender, instance, **kwargs):
    """
    Update quote total and regenerate PDF when quote items change
    """
    quote = instance.quote
    # Use update_fields to prevent triggering other signals unnecessarily
    # Only update if the quote is not currently being converted to invoice
    if not hasattr(quote, '_converting_to_invoice'):
        quote.save(update_fields=['total_amount']) 