from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
import os
import google.generativeai as genai
from .models import ChatHistory

class GeminiChatView(APIView):
    def post(self, request):
        user_message = request.data.get('message')
        if not user_message:
            return Response({'error': 'Message is required.'}, status=status.HTTP_400_BAD_REQUEST)

        api_key = os.getenv('GOOGLE_API_KEY')
        if not api_key:
            return Response({'error': 'Gemini API key not set.'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        try:
            genai.configure(api_key=api_key)
            model = genai.GenerativeModel('gemini-2.5-flash')
            response = model.generate_content([user_message])
        
            reply = getattr(response, 'text', None)
            if reply is None:
                candidates = getattr(response, 'candidates', None)
                if candidates and hasattr(candidates[0], 'content') and hasattr(candidates[0].content, 'parts'):
                    parts = candidates[0].content.parts
                    if parts and hasattr(parts[0], 'text'):
                        reply = parts[0].text
            if not reply:
                return Response({'error': 'Failed to generate reply.'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        except Exception as e:
            return Response({'error': f'Error communicating with Gemini API: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        try:
            ChatHistory.objects.create(user_message=user_message, ai_reply=reply)
        except Exception as e:
            return Response({'error': f'Failed to save chat history: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        return Response({'reply': reply})
