o
    ^i                     @   s`   d dl mZmZ d dlmZ d dlmZ d dlmZ ddl	m
Z
 edgeegdd	 Zd
S )    )api_viewpermission_classes)Responsestatus)AllowAny   )conversationPOSTc                 C   s  | j d}|stdditjdS ztjj|dd	 }|s1tddd	d
d	d	g g dtj
dW S g }|jr?|d|j  g }g }|jr|jdg }|jdg }|jdg }|rst|trgd|nt|}|d|  |rt|trd|nt|}|d|  |rt|trd|nt|}	|d|	  |jr|d|j  |jr|d|j  |rd|nd}
t|
d|j |jpd
|j|j|||j|jd
tj
dW S  ty } ztddt| itjdW  Y d	}~S d	}~ww )aB  
    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errorzphone_number is requiredr   )r   z-started_atz0This is the first conversation with this person.FN )contexthas_previous_conversationlast_conversation_datesummary	sentimentoutcometopicsemotionszSummary of last conversation: r   r   
key_pointsz, zTopics discussed: zEmotions detected: z; zKey points: zSentiment: z	Outcome: 
z6Previous conversation exists but no details available.T)
r   r   r   r   r   r   r   r   call_idr   zAn error occurred: )datagetr   r   HTTP_400_BAD_REQUESTr	   objectsfilterorder_byfirstHTTP_200_OKr   append	meta_data
isinstancelistjoinstrr   r   
started_at	isoformatr   	ExceptionHTTP_500_INTERNAL_SERVER_ERROR)requestr   last_conversationcontext_partsr   r   r   
topics_stremotions_strkey_points_strr   e r2   '/home/nitin/Desktop/jeff/calls/views.pyget_last_conversation   s   
	r4   N)rest_framework.decoratorsr   r   rest_framework.responser   rest_frameworkr   rest_framework.permissionsr   modelsr	   r4   r2   r2   r2   r3   <module>   s    