from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from django.shortcuts import get_object_or_404

from .models import Conversation, Memory, ConversationInsight
from .serializers import ConversationSerializer, MemorySerializer, ConversationInsightSerializer


class ConversationViewSet(viewsets.ReadOnlyModelViewSet):
    """
    ViewSet for viewing conversation data.
    
    Provides read-only access to conversation records and analysis.
    """
    
    permission_classes = []  # Remove authentication requirement for testing
    
    def get_queryset(self):
        """Return all conversations for testing"""
        return Conversation.objects.all().select_related('call', 'call__senior')
    
    def get_serializer_class(self):
        return ConversationSerializer
    
    @action(detail=True, methods=['get'])
    def memories(self, request, pk=None):
        """
        Get memories from a specific conversation.
        
        GET /api/conversations/{id}/memories/
        """
        conversation = self.get_object()
        memories = conversation.memories.all().order_by('-importance_score')
        
        serializer = MemorySerializer(memories, many=True)
        return Response({
            'conversation_id': conversation.id,
            'memories': serializer.data,
        })
    
    @action(detail=False, methods=['get'])
    def analytics(self, request):
        """
        Get conversation analytics for the authenticated user.
        
        GET /api/conversations/analytics/
        """
        conversations = self.get_queryset()
        
        # Calculate analytics
        total_conversations = conversations.count()
        
        # Sentiment analysis
        positive_conversations = conversations.filter(sentiment_score__gt=0.1).count()
        negative_conversations = conversations.filter(sentiment_score__lt=-0.1).count()
        neutral_conversations = conversations.filter(
            sentiment_score__gte=-0.1,
            sentiment_score__lte=0.1
        ).count()
        
        # Engagement analysis
        high_engagement = conversations.filter(engagement_level='high').count()
        medium_engagement = conversations.filter(engagement_level='medium').count()
        low_engagement = conversations.filter(engagement_level='low').count()
        
        # Topic analysis
        all_topics = []
        for conv in conversations:
            all_topics.extend(conv.topics_discussed)
        
        topic_counts = {}
        for topic in all_topics:
            topic_counts[topic] = topic_counts.get(topic, 0) + 1
        
        # Most discussed topics
        most_discussed_topics = sorted(
            topic_counts.items(),
            key=lambda x: x[1],
            reverse=True
        )[:5]
        
        # Recent conversations
        recent_conversations = conversations.order_by('-created_at')[:5]
        recent_data = ConversationSerializer(recent_conversations, many=True).data
        
        return Response({
            'total_conversations': total_conversations,
            'sentiment_breakdown': {
                'positive': positive_conversations,
                'negative': negative_conversations,
                'neutral': neutral_conversations,
            },
            'engagement_breakdown': {
                'high': high_engagement,
                'medium': medium_engagement,
                'low': low_engagement,
            },
            'most_discussed_topics': most_discussed_topics,
            'recent_conversations': recent_data,
        })


class MemoryViewSet(viewsets.ReadOnlyModelViewSet):
    """
    ViewSet for viewing memory data.
    
    Provides read-only access to memory records.
    """
    
    permission_classes = []  # Remove authentication requirement for testing
    
    def get_queryset(self):
        """Return all memories for testing"""
        return Memory.objects.all().select_related('senior', 'conversation')
    
    def get_serializer_class(self):
        return MemorySerializer
    
    @action(detail=False, methods=['get'])
    def by_type(self, request):
        """
        Get memories filtered by type.
        
        GET /api/memories/by_type/?type=story
        """
        memory_type = request.query_params.get('type')
        if not memory_type:
            return Response(
                {'error': 'Type parameter is required'},
                status=status.HTTP_400_BAD_REQUEST
            )
        
        memories = self.get_queryset().filter(memory_type=memory_type)
        serializer = self.get_serializer(memories, many=True)
        
        return Response({
            'type': memory_type,
            'memories': serializer.data,
            'count': memories.count(),
        })
    
    @action(detail=False, methods=['get'])
    def by_senior(self, request):
        """
        Get memories for a specific senior.
        
        GET /api/memories/by_senior/?senior_id=1
        """
        senior_id = request.query_params.get('senior_id')
        if not senior_id:
            return Response(
                {'error': 'Senior ID parameter is required'},
                status=status.HTTP_400_BAD_REQUEST
            )
        
        memories = self.get_queryset().filter(senior_id=senior_id)
        serializer = self.get_serializer(memories, many=True)
        
        return Response({
            'senior_id': senior_id,
            'memories': serializer.data,
            'count': memories.count(),
        })


class ConversationInsightViewSet(viewsets.ReadOnlyModelViewSet):
    """
    ViewSet for viewing conversation insights.
    
    Provides read-only access to insight data.
    """
    
    permission_classes = []  # Remove authentication requirement for testing
    
    def get_queryset(self):
        """Return all insights for testing"""
        return ConversationInsight.objects.all().select_related('senior')
    
    def get_serializer_class(self):
        return ConversationInsightSerializer
    
    @action(detail=False, methods=['get'])
    def by_type(self, request):
        """
        Get insights filtered by type.
        
        GET /api/insights/by_type/?type=mood_trend
        """
        insight_type = request.query_params.get('type')
        if not insight_type:
            return Response(
                {'error': 'Type parameter is required'},
                status=status.HTTP_400_BAD_REQUEST
            )
        
        insights = self.get_queryset().filter(insight_type=insight_type)
        serializer = self.get_serializer(insights, many=True)
        
        return Response({
            'type': insight_type,
            'insights': serializer.data,
            'count': insights.count(),
        })