from datetime import timedelta

import structlog
from django.utils import timezone

from vbv_lernwelt.assignment.models import AssignmentType
from vbv_lernwelt.course.models import CourseSessionUser
from vbv_lernwelt.course_session.models import (
    CourseSessionAssignment,
    CourseSessionEdoniqTest,
)
from vbv_lernwelt.notify.services import NotificationService

logger = structlog.get_logger(__name__)

ASSIGNMENT_REMINDER_LEAD_TIME = timedelta(days=2)


def send_assignment_reminder_notifications():
    start = timezone.now()
    end = timezone.now() + ASSIGNMENT_REMINDER_LEAD_TIME
    sent = []

    # member notifications (CASEWORK and PREP_ASSIGNMENT)
    for assignment in CourseSessionAssignment.objects.filter(
        submission_deadline__start__lte=end,
        submission_deadline__start__gte=start,
        learning_content__assignment_type__in=[
            AssignmentType.CASEWORK.value,
            AssignmentType.PREP_ASSIGNMENT.value,
        ],
    ):
        for member in CourseSessionUser.objects.filter(
            course_session_id=assignment.course_session.id,
            role=CourseSessionUser.Role.MEMBER,
        ):
            sent.append(
                NotificationService.send_assignment_reminder_notification_member(
                    recipient=member.user, assignment=assignment
                )
            )

    # member notifications (EDONIQ_TEST)
    for edoniq_test in CourseSessionEdoniqTest.objects.filter(
        deadline__start__lte=end,
        deadline__start__gte=start,
    ):
        for member in CourseSessionUser.objects.filter(
            course_session_id=edoniq_test.course_session.id,
            role=CourseSessionUser.Role.MEMBER,
        ):
            sent.append(
                NotificationService.send_edoniq_test_reminder_notification_member(
                    recipient=member.user, edoniq_test=edoniq_test
                )
            )

    # expert notifications (CASEWORK)
    for assignment in CourseSessionAssignment.objects.filter(
        evaluation_deadline__start__lte=end,
        evaluation_deadline__start__gte=start,
        learning_content__assignment_type__in=[
            AssignmentType.CASEWORK.value,
        ],
    ):
        for expert in CourseSessionUser.objects.filter(
            course_session_id=assignment.course_session.id,
            role=CourseSessionUser.Role.EXPERT,
        ):
            sent.append(
                NotificationService.send_casework_expert_evaluation_reminder(
                    recipient=expert.user, assignment=assignment
                )
            )

    logger.debug(
        "Sent assigment reminders",
        start_time=start.isoformat(),
        end_time=end.isoformat(),
        label="assigment_reminders",
        sent=sent,
    )

    return {"sent": sent}
