"""
DRF API views for face registration, identification, listing, and deletion.
"""

import logging
import traceback

from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView

from .models import FaceRecord
from .serializers import (
    FaceRecordSerializer,
    IdentifyResultSerializer,
    IdentifySerializer,
    RegisterSerializer,
)
from .services.recognition import FaceRecognitionService

logger = logging.getLogger(__name__)


class RegisterFaceView(APIView):
    """
    POST /api/faces/register/
    Register a new face with a name and photo.
    """

    def post(self, request):
        serializer = RegisterSerializer(data=request.data)
        if not serializer.is_valid():
            return Response(
                {
                    "error": "Invalid input data.",
                    "detail": serializer.errors,
                },
                status=status.HTTP_400_BAD_REQUEST,
            )

        try:
            service = FaceRecognitionService()
            record = service.register_face(
                name=serializer.validated_data["name"],
                image_input=serializer.validated_data["photo"],
                metadata=serializer.validated_data.get("metadata", {}),
            )
            response_serializer = FaceRecordSerializer(record)
            return Response(response_serializer.data, status=status.HTTP_201_CREATED)

        except ValueError as e:
            logger.warning("Face registration failed: %s", str(e))
            return Response(
                {
                    "error": str(e),
                    "detail": "Face detection failed during preprocessing.",
                },
                status=status.HTTP_400_BAD_REQUEST,
            )

        except Exception as e:
            logger.error("Face registration error: %s\n%s", str(e), traceback.format_exc())
            return Response(
                {
                    "error": "An internal error occurred during face registration.",
                    "detail": str(e),
                },
                status=status.HTTP_500_INTERNAL_SERVER_ERROR,
            )


class IdentifyFaceView(APIView):
    """
    POST /api/faces/identify/
    Identify a face by comparing against registered embeddings.
    """

    def post(self, request):
        serializer = IdentifySerializer(data=request.data)
        if not serializer.is_valid():
            return Response(
                {
                    "error": "Invalid input data.",
                    "detail": serializer.errors,
                },
                status=status.HTTP_400_BAD_REQUEST,
            )

        try:
            service = FaceRecognitionService()
            result = service.identify_face(
                image_input=serializer.validated_data["photo"],
            )
            response_serializer = IdentifyResultSerializer(result)
            return Response(response_serializer.data, status=status.HTTP_200_OK)

        except ValueError as e:
            logger.warning("Face identification failed: %s", str(e))
            return Response(
                {
                    "error": str(e),
                    "detail": "Face detection failed during preprocessing.",
                },
                status=status.HTTP_400_BAD_REQUEST,
            )

        except Exception as e:
            logger.error("Face identification error: %s\n%s", str(e), traceback.format_exc())
            return Response(
                {
                    "error": "An internal error occurred during face identification.",
                    "detail": str(e),
                },
                status=status.HTTP_500_INTERNAL_SERVER_ERROR,
            )


class FaceListView(APIView):
    """
    GET /api/faces/
    List all registered faces (without embeddings).
    """

    def get(self, request):
        try:
            service = FaceRecognitionService()
            faces = service.list_registered_faces()
            return Response(faces, status=status.HTTP_200_OK)

        except Exception as e:
            logger.error("Face listing error: %s\n%s", str(e), traceback.format_exc())
            return Response(
                {
                    "error": "An internal error occurred while listing faces.",
                    "detail": str(e),
                },
                status=status.HTTP_500_INTERNAL_SERVER_ERROR,
            )


class FaceDeleteView(APIView):
    """
    DELETE /api/faces/<int:face_id>/
    Delete a registered face by ID.
    """

    def delete(self, request, face_id):
        try:
            service = FaceRecognitionService()
            deleted = service.delete_face(face_id)
            if deleted:
                return Response(status=status.HTTP_204_NO_CONTENT)
            else:
                return Response(
                    {
                        "error": "Face record not found.",
                        "detail": f"No face record with id={face_id} exists.",
                    },
                    status=status.HTTP_404_NOT_FOUND,
                )

        except Exception as e:
            logger.error("Face deletion error: %s\n%s", str(e), traceback.format_exc())
            return Response(
                {
                    "error": "An internal error occurred while deleting the face.",
                    "detail": str(e),
                },
                status=status.HTTP_500_INTERNAL_SERVER_ERROR,
            )


class HealthCheckView(APIView):
    """
    GET /api/health/
    Health check endpoint returning server status and registered face count.
    """

    def get(self, request):
        try:
            count = FaceRecord.objects.count()
            return Response(
                {
                    "status": "ok",
                    "registered_faces": count,
                },
                status=status.HTTP_200_OK,
            )
        except Exception as e:
            logger.error("Health check error: %s", str(e))
            return Response(
                {
                    "status": "error",
                    "registered_faces": 0,
                    "error": str(e),
                },
                status=status.HTTP_500_INTERNAL_SERVER_ERROR,
            )
