from __future__ import annotations


def get_attendance_records(tenant, employee=None, date_from=None, date_to=None,
                           source=None, is_finalized=None):
    from simorgh.apps.hr_core.models import AttendanceRecord

    qs = AttendanceRecord.objects.filter(tenant=tenant).select_related("employee")
    if employee is not None:
        qs = qs.filter(employee=employee)
    if date_from:
        qs = qs.filter(date__gte=date_from)
    if date_to:
        qs = qs.filter(date__lte=date_to)
    if source is not None:
        qs = qs.filter(source=source)
    if is_finalized is not None:
        qs = qs.filter(is_finalized=is_finalized)
    return qs


def get_monthly_summary(tenant, employee, year: int, month: int) -> dict:
    from django.db.models import Sum, Count

    from simorgh.apps.hr_core.models import AttendanceRecord

    qs = AttendanceRecord.objects.filter(
        tenant=tenant,
        employee=employee,
        date__year=year,
        date__month=month,
    )
    agg = qs.aggregate(
        total_days=Count("id"),
        total_work_minutes=Sum("work_minutes"),
        total_overtime_minutes=Sum("overtime_minutes"),
    )
    finalized_days = qs.filter(is_finalized=True).count()
    return {
        "year": year,
        "month": month,
        "employee_id": employee.pk,
        "total_days": agg["total_days"] or 0,
        "finalized_days": finalized_days,
        "total_work_minutes": agg["total_work_minutes"] or 0,
        "total_overtime_minutes": agg["total_overtime_minutes"] or 0,
    }
