from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.permissions import AllowAny
from rest_framework.throttling import AnonRateThrottle

from .serializers import ChatQuerySerializer
from .services import get_ai_response

class ChatAPIView(APIView):
    """
    Endpoint unique pour le chatbot.
    Accepte POST { "message": "...", "conversation_uuid": "..." }
    Retourne { "reply": "...", "conversation_uuid": "..." }
    """
    permission_classes = [AllowAny] # Public
    throttle_classes = [AnonRateThrottle] # Rate limiting par défaut

    def post(self, request, *args, **kwargs):
        serializer = ChatQuerySerializer(data=request.data)
        if serializer.is_valid():
            user_message = serializer.validated_data.get('message')
            conv_uuid = serializer.validated_data.get('conversation_uuid')

            # Appel au service (Logique métier)
            result = get_ai_response(user_message, conv_uuid)

            return Response(result, status=status.HTTP_200_OK)

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)