# sheets/signals.py
from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver
from django.db.models import Sum
from django.db.models.functions import Coalesce
from decimal import Decimal

# IMPORT THE MODELS AT THE TOP
from .models import ExcelEntry, SecondTableEntry, MonthlySheet, Cell

@receiver([post_save, post_delete], sender=ExcelEntry)
def update_top_right_helium_input(sender, instance, **kwargs):
    """Update top-right table when ExcelEntry changes"""
    if instance.date:
        # Get the monthly sheet for this date
        sheet = MonthlySheet.objects.filter(
            year=instance.date.year,
            month=instance.date.month
        ).first()
        
        if sheet:
            # Re-populate helium input data
            from .views import MonthlySheetView
            view = MonthlySheetView()
            view.populate_helium_input_to_top_right(sheet)

@receiver([post_save, post_delete], sender=SecondTableEntry)
def update_monthly_sheet_bezug(sender, instance, **kwargs):
    """Update B11 (Bezug) in monthly sheet when SecondTableEntry changes - ONLY for non-start sheets"""
    if instance.date and instance.client:
        # Check if this is the start sheet (2025-01)
        if instance.date.year == 2025 and instance.date.month == 1:
            return  # Don't auto-update for start sheet
        
        # Get or create the monthly sheet for this date
        sheet, created = MonthlySheet.objects.get_or_create(
            year=instance.date.year,
            month=instance.date.month
        )
        
        # Calculate total LHe output for this client in this month
        lhe_output_sum = SecondTableEntry.objects.filter(
            client=instance.client,
            date__year=instance.date.year,
            date__month=instance.date.month
        ).aggregate(
            total=Coalesce(Sum('lhe_output'), Decimal('0'))
        )['total']
        
        # Update B11 cell (row_index 8 = Excel B11) in TOP-LEFT table
        b11_cell_left = Cell.objects.filter(
            sheet=sheet,
            table_type='top_left',
            client=instance.client,
            row_index=8  # Excel B11
        ).first()
        
        if b11_cell_left and (b11_cell_left.value != lhe_output_sum or b11_cell_left.value is None):
            b11_cell_left.value = lhe_output_sum
            b11_cell_left.save()
            
            # Import here to avoid circular imports
            from .views import SaveCellsView
            save_view = SaveCellsView()
            save_view.calculate_top_left_dependents(sheet, b11_cell_left)
        
        # ALSO update Bezug (row_index 8) in TOP-RIGHT table
        b11_cell_right = Cell.objects.filter(
            sheet=sheet,
            table_type='top_right',
            client=instance.client,
            row_index=8  # Excel row 12 = Bezug
        ).first()
        
        if b11_cell_right and (b11_cell_right.value != lhe_output_sum or b11_cell_right.value is None):
            b11_cell_right.value = lhe_output_sum
            b11_cell_right.save()
            
            # Also trigger top-right calculations
            from .views import SaveCellsView
            save_view = SaveCellsView()
            save_view.calculate_top_right_dependents(sheet, b11_cell_right)