from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver
from django.db.models import Avg
from .models import ReportCard, ReportCardDetail

@receiver(post_save, sender=ReportCardDetail)
@receiver(post_delete, sender=ReportCardDetail)
def update_reportcard_average(sender, instance, **kwargs):
    reportcard = instance.reportcard  # کارنامه مربوطه
    details = reportcard.details.all()  # تمام جزئیات مرتبط
    if details.exists():
        reportcard.average_score = details.aggregate(Avg('score'))['score__avg']  # میانگین نمرات
    else:
        reportcard.average_score = 0  # اگر هیچ نمره‌ای نباشه
    reportcard.save()
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.db.models import Avg
from .models import*

@receiver(post_save, sender=ReportCard)
def calculate_cultural_scores(sender, instance, created, **kwargs):
    if instance.title in ["نهایی", "مستمر"] and created:
        person = instance.person  
        start_date = instance.date.start_date
        end_date = instance.date.end_date

        # پیدا کردن کارنامه‌های فرهنگی
        cultural_reportcards = ReportCard.objects.filter(
            person=person,
            title="فرهنگی",
            date__start_date__gte=start_date,
            date__end_date__lte=end_date
        )

        # محاسبه میانگین نمرات
        avg_score = 0
        if cultural_reportcards.exists():
            avg_score = ReportCardDetail.objects.filter(
                reportcard__in=cultural_reportcards
            ).aggregate(Avg('score'))['score__avg'] or 0

        # پیدا کردن کارنامه نهایی مرتبط با این شخص
        try:
            final_report_card = ReportCardFinaly.objects.get(person=person, title=instance)
            final_report_card.sargroh = avg_score
            final_report_card.save(update_fields=["sargroh"])
        except ReportCardFinaly.DoesNotExist:
            print("ssss.")

        print(f"ssss{avg_score}")



from django.db.models.signals import post_save
from django.dispatch import receiver
from django.db.models import Avg
from .models import ReportCardDetail, ReportCard, ReportCardFinaly

@receiver(post_save, sender=ReportCardDetail)
def update_sargroh(sender, instance, **kwargs):
    report_card = instance.reportcard
    person = report_card.person

    # دریافت همه‌ی کارنامه‌های نهایی و مستمر این شخص
    final_reports = ReportCardFinaly.objects.filter(
        person=person,
        title__title__in=["نهایی", "مستمر"]
    )

    for final_report in final_reports:
        start_date = final_report.title.date.start_date
        end_date = final_report.title.date.end_date

        # پیدا کردن کارنامه‌های فرهنگی مربوط به بازه‌ی تاریخی
        cultural_reportcards = ReportCard.objects.filter(
            person=person,
            title="فرهنگی",
            date__start_date__gte=start_date,
            date__end_date__lte=end_date,
        )

        # محاسبه میانگین نمرات
        avg_score = ReportCardDetail.objects.filter(
            reportcard__in=cultural_reportcards
        ).aggregate(Avg('score'))['score__avg']

        # ذخیره مقدار جدید در فیلد sargroh
        new_sargroh = avg_score or 0
        if final_report.sargroh != new_sargroh:  # جلوگیری از آپدیت غیرضروری
            final_report.sargroh = new_sargroh
            final_report.save(update_fields=['sargroh'])  # فقط فیلد sargroh را آپدیت می‌کند
