from django.shortcuts import render
from common.views import *
from rest_framework import generics
from django.http import JsonResponse
from openai import OpenAI
from .models import *
from .serializers import *
from django_filters.rest_framework import DjangoFilterBackend
from mama_care_api.settings import OPENAI_API_KEY
# Create your views here.

client = OpenAI(api_key=OPENAI_API_KEY)

SYSTEM_PROMPT = """
You are Mama Care AI, a warm, supportive, and trustworthy assistant
for mothers and caregivers.

You support:
- Pregnancy and prenatal care
- Postpartum recovery after birth
- Newborn, infant, toddler, and child care
- Child development and well-being up to 10 years old

Important:
The information provided is for educational and informational purposes only.
It is not medical advice, diagnosis, or treatment.

When discussing health-related or medical topics,
gently remind the user that the information provided is general guidance
and not a substitute for professional medical advice.
Do not repeat this reminder unnecessarily.

You are strictly limited to pregnancy, postpartum care,
newborn care, child development, and parenting topics
for children up to 10 years old.

If a user asks about topics unrelated to motherhood,
pregnancy, child care, health, or parenting,
politely refuse and redirect the conversation back
to Mama Care topics.

Do not answer unrelated questions.

Rules:
- Provide general educational guidance and emotional support only
- Do NOT diagnose medical conditions
- Do NOT prescribe medications or provide dosages
- For serious, urgent, or worsening symptoms, clearly recommend consulting
  a licensed healthcare professional
- If a situation appears life-threatening, recommend immediate medical care
- Use calm, reassuring, and non-alarming language
- Be empathetic, respectful, and culturally sensitive
- Keep answers clear, simple, and practical
- Avoid fear-based or judgmental language
"""

class SendMessage(generics.GenericAPIView):
    authentication_classes = [APIKeyAuthentication,MobileTokenAuthentication]

    def post(self, request, *args, **kwargs):
        """
            Expected request body:
            {
                "messages": [
                    {"role": "user", "content": "I feel tired during pregnancy"}
                ]
            }
            """

        try:
            subscriptionPlanId = request.data.get("subscriptionPlanId", None)
            messages = request.data.get("messages", [])
            dataList =  SubscriptionPlan.objects.filter(id = subscriptionPlanId)
            selected = None
            if dataList.__len__() > 0:
                selected = dataList[0]
            
            if selected is not None:
                if selected.aiAssistModel != '':
                    if not messages:
                        return JsonResponse(
                            {"error": "Messages are required."},
                            status=400
                        )

                    # ✅ Limit context (VERY IMPORTANT for cost control)
                    #messages = messages[-6:]  # last 6 messages only

                    # ✅ GPT-5 API call (Responses API)
                    response = client.responses.create(
                        #gpt-5-mini
                        #gpt-4o-mini
                        model=selected.aiAssistModel,
                        input=[
                            {"role": "system", "content": SYSTEM_PROMPT},
                            *messages
                        ],
                        max_output_tokens=400,
                    )

                    reply_text = response.output_text

                    return JsonResponse({
                        "subscriptionPlanId":subscriptionPlanId,
                        "messages":messages,
                        "reply": reply_text
                    })
                else:
                    return JsonResponse({
                        "subscriptionPlanId":subscriptionPlanId,
                        "messages":messages,
                        "reply": "No Model in basic Plan"
                    })
            else:
                return JsonResponse({
                    "subscriptionPlanId":subscriptionPlanId,
                    "messages":messages,
                    "reply": "Model is required"
                },status = 400)

        except Exception as e:
            print(f"OpenAI error: {str(e)}")
            #logger.error(f"OpenAI error: {str(e)}")

            return JsonResponse({
                "subscriptionPlanId":subscriptionPlanId,
                "messages":messages,
                "reply": "I'm sorry, something went wrong. Please try again shortly."
            }, status=500)

class CheckAIAssist:
    def get_queryset(self):
        return super().get_queryset()
        
    def perform_create(self, serializer):
        return super().perform_create(serializer)

    def perform_update(self, serializer):
        return super().perform_update(serializer)

    def perform_destroy(self, model):
        return super().perform_destroy(model)

#AIAssist Settings
class AIAssistSettingsListMobileView(SubscriptionPlanMixin,CheckAIAssist,generics.ListCreateAPIView):
    authentication_classes = [APIKeyAuthentication, MobileTokenAuthentication]
    pagination_class = StandardSetPagination
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ["parentId"]
    queryset = AIAssistSettings.objects.all().order_by('createdDate')
    serializer_class = AIAssistSettingsSerializer


class AIAssistSettingsDetailMobileView(SubscriptionPlanMixin,generics.RetrieveUpdateDestroyAPIView):
    authentication_classes = [APIKeyAuthentication, MobileTokenAuthentication]
    pagination_class = StandardSetPagination
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ["parentId"]
    lookup_field = "parentId"
    queryset = AIAssistSettings.objects.all().order_by('createdDate')
    serializer_class = AIAssistSettingsSerializer


class AIAssistSettingsListDashboardView(generics.ListCreateAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    pagination_class = StandardSetPagination
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ["parentId"]
    queryset = AIAssistSettings.objects.all().order_by('createdDate')
    serializer_class = AIAssistSettingsSerializer


class AIAssistSettingsDetailDashboardView(generics.RetrieveUpdateDestroyAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ["parentId"]
    lookup_field = "id"
    queryset = AIAssistSettings.objects.all().order_by('createdDate')
    serializer_class = AIAssistSettingsSerializer


#Chat
class ChatListMobileView(SubscriptionPlanMixin,CheckAIAssist,generics.ListCreateAPIView):
    authentication_classes = [APIKeyAuthentication, MobileTokenAuthentication]
    pagination_class = StandardSetPagination
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ["parentId"]
    queryset = Chat.objects.all().order_by('createdDate')
    serializer_class = ChatSerializer


class ChatDetailMobileView(SubscriptionPlanMixin,generics.DestroyAPIView):
    authentication_classes = [APIKeyAuthentication, MobileTokenAuthentication]
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ["parentId"]
    lookup_field = "id"
    queryset = Chat.objects.all().order_by('createdDate')
    serializer_class = ChatSerializer


class ChatListDashboardView(generics.ListCreateAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    pagination_class = StandardSetPagination
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ["parentId"]
    queryset = Chat.objects.all().order_by('createdDate')
    serializer_class = ChatSerializer


class ChatDetailDashboardView(generics.RetrieveUpdateDestroyAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ["parentId"]
    lookup_field = "id"
    queryset = Chat.objects.all().order_by('createdDate')
    serializer_class = ChatSerializer


#Message
class MessageListMobileView(SubscriptionPlanMixin,generics.ListCreateAPIView):
    authentication_classes = [APIKeyAuthentication, MobileTokenAuthentication]
    pagination_class = StandardSetPagination
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ["chatId"]
    queryset = Message.objects.all().order_by('createdDate')
    serializer_class = MessageSerializer


class MessageDetailMobileView(SubscriptionPlanMixin,generics.RetrieveUpdateDestroyAPIView):
    authentication_classes = [APIKeyAuthentication, MobileTokenAuthentication]
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ["chatId"]
    lookup_field = "id"
    queryset = Message.objects.all().order_by('createdDate')
    serializer_class = MessageSerializer

class MessageListDashboardView(generics.ListCreateAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    pagination_class = StandardSetPagination
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ["chatId"]
    queryset = Message.objects.all().order_by('createdDate')
    serializer_class = MessageSerializer


class MessageDetailDashboardView(generics.RetrieveUpdateDestroyAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ["chatId"]
    lookup_field = "id"
    queryset = Message.objects.all().order_by('createdDate')
    serializer_class = MessageSerializer
