"""
Счётчики для бейджей нижнего меню навигации (один запрос).
"""
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from django.utils import timezone
from django.db.models import Sum, Q

from .models import MentorStudentConnection, Client


class NavBadgesView(APIView):
    """
    GET /api/users/nav-badges/
    Возвращает: lessons_today, chat_unread, homework_pending, feedback_pending
    """
    permission_classes = [IsAuthenticated]

    def get(self, request):
        user = request.user
        today = timezone.now().date()

        # Занятий сегодня: ментор — запланированные/идущие; студент — его занятия на сегодня
        lessons_today = 0
        if user.role == 'mentor':
            from apps.schedule.models import Lesson
            lessons_today = Lesson.objects.filter(
                mentor=user,
                start_time__date=today,
                status__in=['scheduled', 'in_progress']
            ).count()
        elif user.role == 'client':
            from apps.schedule.models import Lesson
            client = Client.objects.filter(user=user).first()
            if client:
                lessons_today = Lesson.objects.filter(
                    client=client,
                    start_time__date=today,
                    status__in=['scheduled', 'in_progress']
                ).count()

        # Непрочитанных сообщений в чатах
        chat_unread = 0
        from apps.chat.models import ChatParticipant
        agg = ChatParticipant.objects.filter(user=user).aggregate(total=Sum('unread_count'))
        chat_unread = agg['total'] or 0

        # ДЗ: непроверенные + «заполнить позже» (для ментора); для клиента/родителя — 0 или свои на проверке
        homework_pending = 0
        if user.role == 'mentor':
            from apps.homework.models import Homework, HomeworkSubmission
            fill_later_count = Homework.objects.filter(mentor=user, fill_later=True).count()
            unchecked = HomeworkSubmission.objects.filter(
                homework__mentor=user,
                status__in=['pending', 'checking']
            ).count()
            homework_pending = fill_later_count + unchecked
        elif user.role == 'client':
            from apps.homework.models import HomeworkSubmission
            homework_pending = HomeworkSubmission.objects.filter(
                student=user,
                status__in=['pending', 'checking']
            ).count()

        # Запросы на менторство: ожидающие ответа ментора
        mentorship_requests_pending = 0
        if user.role == 'mentor':
            mentorship_requests_pending = MentorStudentConnection.objects.filter(
                mentor=user,
                status=MentorStudentConnection.STATUS_PENDING_MENTOR,
                initiator=MentorStudentConnection.INITIATOR_STUDENT,
            ).count()

        # Обратная связь не дана: завершённые занятия (ментор, не групповые) без оценки и заметок
        feedback_pending = 0
        if user.role == 'mentor':
            from apps.schedule.models import Lesson
            feedback_pending = Lesson.objects.filter(
                mentor=user,
                status='completed',
                group__isnull=True,
                mentor_grade__isnull=True,
                school_grade__isnull=True,
            ).filter(
                Q(mentor_notes__isnull=True) | Q(mentor_notes='')
            ).count()

        return Response({
            'lessons_today': max(0, lessons_today),
            'chat_unread': max(0, chat_unread),
            'homework_pending': max(0, homework_pending),
            'feedback_pending': max(0, feedback_pending),
            'mentorship_requests_pending': max(0, mentorship_requests_pending),
        })
