from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
from rest_framework import status
from rest_framework.permissions import AllowAny
from .models import conversation


@api_view(['POST'])
@permission_classes([AllowAny])  # Allow external calls from Vapi
def get_last_conversation(request):
    """
    Endpoint for Vapi to fetch the last conversation for a phone number.
    
    Expected request body:
    {
        "phone_number": "+49123456789"
    }
    
    Returns:
    {
        "context": "Summary of last conversation...",
        "has_previous_conversation": true,
        "last_conversation_date": "2024-01-15T10:30:00Z",
        "summary": "...",
        "sentiment": "positive",
        "outcome": "successful",
        "topics": ["topic1", "topic2"],  # from meta_data if available
        "emotions": ["happy", "calm"]  # from meta_data if available
    }
    """
    phone_number = request.data.get('phone_number')
    print("=========================",phone_number)
    
    if not phone_number:
        return Response(
            {'error': 'phone_number is required'},
            status=status.HTTP_400_BAD_REQUEST
        )
    
    # Query the conversations table for the most recent conversation for this phone number
    try:
        last_conversation = conversation.objects.filter(
            phone_number=phone_number
        ).order_by('-started_at').first()
        
        if not last_conversation:
            # No previous conversation found
            return Response({
                'context': 'This is the first conversation with this person.',
                'has_previous_conversation': False,
                'last_conversation_date': None,
                'summary': '',
                'sentiment': None,
                'outcome': None,
                'topics': [],
                'emotions': []
            }, status=status.HTTP_200_OK)
        
        # Build context string from conversation data
        context_parts = []
        
        if last_conversation.summary:
            context_parts.append(f"Summary of last conversation: {last_conversation.summary}")
        
        # Extract topics and emotions from meta_data if available
        topics = []
        emotions = []
        if last_conversation.meta_data:
            topics = last_conversation.meta_data.get('topics', [])
            emotions = last_conversation.meta_data.get('emotions', [])
            key_points = last_conversation.meta_data.get('key_points', [])
            
            if topics:
                topics_str = ", ".join(topics) if isinstance(topics, list) else str(topics)
                context_parts.append(f"Topics discussed: {topics_str}")
            
            if emotions:
                emotions_str = ", ".join(emotions) if isinstance(emotions, list) else str(emotions)
                context_parts.append(f"Emotions detected: {emotions_str}")
            
            if key_points:
                key_points_str = "; ".join(key_points) if isinstance(key_points, list) else str(key_points)
                context_parts.append(f"Key points: {key_points_str}")
        
        if last_conversation.sentiment:
            context_parts.append(f"Sentiment: {last_conversation.sentiment}")
        
        if last_conversation.outcome:
            context_parts.append(f"Outcome: {last_conversation.outcome}")
        
        context = "\n".join(context_parts) if context_parts else "Previous conversation exists but no details available."
        
        return Response({
            'context': context,
            'has_previous_conversation': True,
            'last_conversation_date': last_conversation.started_at.isoformat(),
            'summary': last_conversation.summary or '',
            'sentiment': last_conversation.sentiment,
            'outcome': last_conversation.outcome,
            'topics': topics,
            'emotions': emotions,
            'call_id': last_conversation.call_id,
            'status': last_conversation.status
        }, status=status.HTTP_200_OK)
            
    except Exception as e:
        return Response(
            {'error': f'An error occurred: {str(e)}'},
            status=status.HTTP_500_INTERNAL_SERVER_ERROR
        )
