from django.db.models.signals import post_save, pre_save
from django.dispatch import receiver
from django.db import models
from decimal import Decimal

# DISABLED: This signal was creating duplicate receipts because Repayment.save() 
# already calls create_or_update_receipt() which handles receipt creation.
# Keeping both active caused duplicate receipt creation on every repayment.
#
# @receiver(post_save, sender='loans.Repayment')
# def create_receipt_for_repayment(sender, instance, created, **kwargs):
#     """Automatically create receipt when repayment is saved"""
#     if created:
#         from utils.models import Receipt
#         
#         # Check if receipt already exists
#         try:
#             _ = instance.receipt
#             return  # Receipt already exists
#         except Exception:
#             pass
#         
#         try:
#             # Calculate balances
#             loan = instance.loan
#             
#             # Get all repayments before this one for the same loan
#             previous_total = sender.objects.filter(
#                 loan=loan,
#                 payment_date__lt=instance.payment_date
#             ).aggregate(total=models.Sum('amount'))['total']
#             
#             # Ensure previous_total is Decimal (Sum can return float)
#             if previous_total is None:
#                 previous_total = Decimal('0')
#             elif not isinstance(previous_total, Decimal):
#                 previous_total = Decimal(str(previous_total))
#             
#             previous_balance = loan.principal_amount - previous_total
#             new_balance = previous_balance - instance.amount
#             
#             # Create receipt
#             Receipt.objects.create(
#                 repayment=instance,
#                 loan=loan,
#                 borrower=loan.borrower,
#                 amount_paid=instance.amount,
#                 payment_method=instance.payment_method,
#                 payment_date=instance.payment_date,
#                 previous_balance=previous_balance,
#                 new_balance=new_balance
#             )
#             
#             print(f"SUCCESS: Created receipt for repayment {instance.receipt_number}")
#             
#         except Exception as e:
#             print(f"ERROR: Error creating receipt for repayment {instance.id}: {e}")


@receiver(post_save, sender='loans.Repayment')
def recalculate_loan_on_payment(sender, instance, created, **kwargs):
    """
    Trigger recalculation when payment is recorded.
    
    Validates: Requirements 9.6, 9.7, 9.8
    """
    # Avoid infinite recursion by checking if we're already in a save operation
    if hasattr(instance, '_recalculating'):
        return
    
    try:
        # Mark that we're recalculating to avoid recursion
        instance._recalculating = True
        
        # Update loan's amount_paid cache
        from django.db.models import Sum
        loan = instance.loan
        total_paid = loan.repayments.aggregate(
            total=Sum('amount')
        )['total'] or Decimal('0.00')
        
        loan._amount_paid_cache = total_paid
        loan.last_payment_date = instance.payment_date
        
        # Recalculate amounts (this will update total_amount and outstanding_amount)
        # Note: outstanding_amount is a property, so it's automatically recalculated
        loan.save(update_fields=['_amount_paid_cache', 'last_payment_date'])
        
    except Exception as e:
        print(f"ERROR: Error recalculating loan amounts after payment: {e}")
    finally:
        # Clean up the flag
        if hasattr(instance, '_recalculating'):
            delattr(instance, '_recalculating')


@receiver(post_save, sender='loans.PenaltyCharge')
def recalculate_loan_on_penalty(sender, instance, created, **kwargs):
    """
    Trigger recalculation when penalty is added.
    
    Validates: Requirements 9.6, 9.7, 9.8
    """
    # Avoid infinite recursion
    if hasattr(instance, '_recalculating'):
        return
    
    try:
        # Mark that we're recalculating
        instance._recalculating = True
        
        # Recalculate loan amounts
        # Note: outstanding_amount is a property that includes penalties,
        # so it will be automatically recalculated when accessed
        loan = instance.loan
        
        # Just touch the loan to update the updated_at timestamp
        # The outstanding_amount property will automatically include the new penalty
        loan.save(update_fields=['updated_at'])
        
    except Exception as e:
        print(f"ERROR: Error recalculating loan amounts after penalty: {e}")
    finally:
        if hasattr(instance, '_recalculating'):
            delattr(instance, '_recalculating')


@receiver(pre_save, sender='loans.Loan')
def recalculate_loan_on_edit(sender, instance, **kwargs):
    """
    Enforce: total_amount always equals principal_amount.

    The company pre-deducts interest and processing fees before disbursement,
    so the principal_amount entered in the system IS the full amount the
    customer must repay. Interest and processing_fee fields are stored for
    internal accounting only and must never inflate the customer-facing balance.

    Validates: Requirements 9.6, 9.7, 9.8
    """
    # Avoid infinite recursion
    if hasattr(instance, '_recalculating'):
        return

    try:
        instance._recalculating = True

        if not instance.pk:
            # New loan — total_amount always equals principal_amount
            instance.total_amount = instance.principal_amount.quantize(Decimal('0.01'))
        else:
            # Existing loan — only sync total_amount when principal_amount changes.
            # Changing interest_amount or processing_fee is for accounting records only
            # and must NOT change what the customer owes.
            #
            # Exception: rollover saves set is_rolled_over=True and have already
            # computed total_amount = principal + rollover_fee correctly.
            # We must not flatten that back to just principal.
            try:
                old_instance = sender.objects.get(pk=instance.pk)
                is_rollover_save = (
                    instance.is_rolled_over and not old_instance.is_rolled_over
                ) or getattr(instance, '_rollover_in_progress', False)
                if is_rollover_save:
                    # Rollover fee is a real customer charge included in total_amount.
                    # Leave total_amount as set by the rollover approve() method.
                    pass
                elif instance.is_rolled_over:
                    # Already a rolled-over loan — total_amount = principal + rollover_fee.
                    # Never flatten it back to just principal, even if principal changes.
                    pass
                elif old_instance.principal_amount != instance.principal_amount:
                    instance.total_amount = instance.principal_amount.quantize(Decimal('0.01'))
                # If only interest/fee changed, leave total_amount untouched.
            except sender.DoesNotExist:
                instance.total_amount = instance.principal_amount.quantize(Decimal('0.01'))

    except Exception as e:
        print(f"ERROR: Error recalculating loan amounts on save: {e}")
    finally:
        if hasattr(instance, '_recalculating'):
            delattr(instance, '_recalculating')