from django.http.response import JsonResponse
from rest_framework.views import APIView
from rest_framework import status
from drf_yasg.utils import swagger_auto_schema
from drf_yasg import openapi
from django.db.models import Q

from Subscriptions.serializers import StudentByRFCreationSerializer, RegistrationFormByParentSerializer, StudentSerializer
from Subscriptions.models import Student, RegistrationForm

from N3wtSchool import bdd

class StudentView(APIView):
    """
    Gère la lecture d’un élève donné.
    """
    @swagger_auto_schema(
        operation_summary="Récupérer les informations d'un élève",
        operation_description="Retourne les détails d'un élève spécifique à partir de son ID",
        responses={
            200: openapi.Response('Détails de l\'élève', StudentSerializer),
            404: openapi.Response('Élève non trouvé')
        },
        manual_parameters=[
            openapi.Parameter(
                'id', openapi.IN_PATH,
                description="ID de l'élève",
                type=openapi.TYPE_INTEGER,
                required=True
            )
        ]
    )
    def get(self, request, id):
        student = bdd.getObject(_objectName=Student, _columnName='id', _value=id)
        if student is None:
            return JsonResponse({"errorMessage":'Aucun élève trouvé'}, safe=False, status=status.HTTP_404_NOT_FOUND)
        student_serializer = StudentSerializer(student)
        return JsonResponse(student_serializer.data, safe=False)

# API utilisée pour la vue de création d'un DI
class StudentListView(APIView):
    """
    Pour la vue de création d’un dossier d’inscription : liste les élèves disponibles.
    """
    @swagger_auto_schema(
        operation_summary="Lister tous les élèves",
        operation_description="Retourne la liste de tous les élèves inscrits ou en cours d'inscription",
        responses={
            200: openapi.Response('Liste des élèves', StudentByRFCreationSerializer(many=True))
        },
        manual_parameters=[
            openapi.Parameter(
                'establishment_id', openapi.IN_QUERY,
                description="ID de l'établissement",
                type=openapi.TYPE_INTEGER,
                required=True
            ),
            openapi.Parameter(
                'school_year', openapi.IN_QUERY,
                description="Année scolaire (ex: 2025-2026)",
                type=openapi.TYPE_STRING,
                required=False
            )
        ]
    )
    # Récupération de la liste des élèves inscrits ou en cours d'inscriptions
    def get(self, request):
        establishment_id = request.GET.get('establishment_id', None)
        status_filter = request.GET.get('status', None)  # Nouveau filtre optionnel
        school_year_filter = request.GET.get('school_year', None)  # Filtre année scolaire

        if establishment_id is None:
            return JsonResponse({'error': 'establishment_id est requis'}, safe=False, status=status.HTTP_400_BAD_REQUEST)

        students_qs = Student.objects.filter(registrationform__establishment_id=establishment_id)

        if status_filter:
            students_qs = students_qs.filter(registrationform__status=status_filter)

        if school_year_filter:
            students_qs = students_qs.filter(registrationform__school_year=school_year_filter)

        students_qs = students_qs.distinct()
        students_serializer = StudentByRFCreationSerializer(students_qs, many=True)
        return JsonResponse(students_serializer.data, safe=False)


# API utilisée pour la vue parent
class ChildrenListView(APIView):
    """
    Pour la vue parent : liste les élèves rattachés à un profil donné.
    """
    @swagger_auto_schema(
        operation_summary="Lister les élèves d'un parent",
        operation_description="Retourne la liste des élèves associés à un profil parent spécifique",
        responses={
            200: openapi.Response('Liste des élèves du parent', RegistrationFormByParentSerializer(many=True))
        },
        manual_parameters=[
            openapi.Parameter(
                'id', openapi.IN_PATH,
                description="ID du profil parent",
                type=openapi.TYPE_INTEGER,
                required=True
            )
        ]
    )
    # Récupération des élèves d'un parent
    # idProfile : identifiant du profil connecté rattaché aux fiches d'élèves
    def get(self, request, id):
        establishment_id = request.GET.get('establishment_id', None)
        if establishment_id is None:
            return JsonResponse({'error': 'establishment_id est requis'}, safe=False, status=status.HTTP_400_BAD_REQUEST)
        
        students = bdd.getObjects(_objectName=RegistrationForm, _columnName='student__guardians__profile_role__profile__id', _value=id)
        if students:
            students = students.filter(
            establishment=establishment_id,
            status__in=[
                RegistrationForm.RegistrationFormStatus.RF_SENT,
                RegistrationForm.RegistrationFormStatus.RF_UNDER_REVIEW,
                RegistrationForm.RegistrationFormStatus.RF_SEPA_SENT,
                RegistrationForm.RegistrationFormStatus.RF_SEPA_TO_SEND,
                RegistrationForm.RegistrationFormStatus.RF_VALIDATED
            ]
        ).distinct()
        students_serializer = RegistrationFormByParentSerializer(students, many=True)
        return JsonResponse(students_serializer.data, safe=False)

def search_students(request):
    """
    API pour rechercher des étudiants en fonction d'un terme de recherche (nom/prénom) et d'un établissement.
    """
    query = request.GET.get('q', '').strip()
    establishment_id = request.GET.get('establishment_id', None)

    if not query:
        return JsonResponse([], safe=False)

    if not establishment_id:
        return JsonResponse({'error': 'establishment_id est requis'}, safe=False, status=status.HTTP_400_BAD_REQUEST)

    # Recherche sur Student (nom ou prénom) et filtrage par établissement via RegistrationForm
    students = Student.objects.filter(
        Q(last_name__icontains=query) | Q(first_name__icontains=query),
        registrationform__establishment_id=establishment_id
    ).distinct()

    results = [
        {
            'id': student.id,
            'first_name': student.first_name,
            'last_name': student.last_name,
            'level': getattr(student.level, 'name', ''),
            'associated_class_name': student.associated_class.atmosphere_name if student.associated_class else '',
            'photo': student.photo.url if student.photo else None
        }
        for student in students
    ]

    return JsonResponse(results, safe=False)