o
    y	i>+                     @   sn   d Z ddlZddlZddlZddlmZ ddlmZmZmZm	Z	 ddl
mZ eeZG dd dZe ZdS )zk
Conversation Summary Service for Voice Bot
Handles conversation summarization and sending to external API
    N)datetime)DictListOptionalAny)Configc                   @   s   e Zd ZdZdd Zdeeef defddZde	e defd	d
Z
dededeeef defddZdeeef fddZdS )ConversationSummaryServicez9Manages conversation summarization and API communication.c                 C   sB   t j| _t j| _t j| _| jrtd| j  d S td d S )Nz4Conversation Summary Service initialized - API URL: z%Conversation Summary Service disabled)	r   ZSUMMARY_API_ENABLEDenabledZSUMMARY_API_URLapi_urlZSUMMARY_API_TIMEOUTtimeoutloggerinfo)self r   (services/conversation_summary_service.py__init__   s   z#ConversationSummaryService.__init__session_datareturnc                 C   s  zQ| dd}| dd}| dd}| dd}| dg }| dg }| d	t }t|trGzt|d
d}W n   t }Y |d}	dd| d| d| d|	 d| ddt d ddg	}
|st|r%|
d g }|D ].}t|t	r| d| dt|}| dd}|d||d q}|dt|dd q}|D ].}t|t	r| d| dt|}| dd}|d||d q|dt|dd qz
|j
dd d  W n   Y t|d!D ]2\}}|d" dkrd#nd$}t|d d%kr|d d&d% d' n|d }|
| d(| d)|  qn|
d* |
dd+d,| | d-d.| dd/t|t|  dd0d1d2d3g d4|
W S  tyt } ztd5|  d6t| W  Y d&}~S d&}~ww )7z
        Create a conversation summary from session data.
        
        Args:
            session_data: Dictionary containing conversation data
            
        Returns:
            Formatted conversation summary string
        business_idUnknowncall_idphone_numbercall_durationr   user_messagesbot_messagescall_start_timeZz+00:00z%Y-%m-%d %H:%M:%Sz=== CALL TRANSFER SUMMARY ===zBusiness ID: z	Call ID: zPhone Number: zCall Start Time: zCall Duration: z secondszTransfer Time:  z=== CONVERSATION SUMMARY ===zConversation Flow:contentmessage	timestampuser)typer   r    Zbotc                 S   s   |  ddS )Nr    r   )get)xr   r   r   <lambda>r   s    zHConversationSummaryService.create_conversation_summary.<locals>.<lambda>)key   r"   ZUSERZBOT   N...z. [z] z(No detailed conversation data available.z=== KEY POINTS ===z- Customer called regarding: z,- Customer requested transfer to human agentz'- Call was handled by AI assistant for z- Total messages exchanged: z=== NEXT STEPS ===z%- Continue conversation with customerz4- Address any unresolved issues from AI conversationz?- Provide personalized assistance based on conversation context
z%Error creating conversation summary: zError creating summary: )r#   r   now
isinstancestrZfromisoformatreplacestrftimeappenddictsort	enumeratelenextend_extract_topicjoin	Exceptionr   error)r   r   r   r   r   r   r   r   r   Zstart_time_strZsummary_partsZall_messagesmsgr   r    iZmsg_typeer   r   r   create_conversation_summary   s   












.

z6ConversationSummaryService.create_conversation_summaryr   c              	   C   s   zH|sW dS |D ]=}t |tr|d|dt|}nt|}t| dkrE|dd }t|dkr@|dd d	   W S |  W S qW dS    Y dS )
z*Extract the main topic from user messages.zGeneral inquiryr   r   
   .r   2   Nr)   )r,   r1   r#   r-   r4   stripsplit)r   r   r:   r   Zfirst_sentencer   r   r   r6      s    

z)ConversationSummaryService._extract_topicr   r   c              
      s  | j std dS z`| |}|||t  dd}td| d| j  tj	| j|ddi| j
d	}|jd
krOtd|  td|j  W dS td|  td|j  td|j  W dS  tjjy   td|  Y dS  tjjy   td|  Y dS  tjjy } ztd| dt|  W Y d}~dS d}~w ty } ztd| dt|  W Y d}~dS d}~ww )a  
        Send conversation summary to external API.
        
        Args:
            business_id: Business ID
            call_id: Call ID
            session_data: Session data for summary creation
            
        Returns:
            True if successful, False otherwise
        z$Conversation summary API is disabledFzUser requested human agent)ZbidZcallidZconversation_summaryr    Ztransfer_reasonz&Sending conversation summary for call z to zContent-Typezapplication/json)jsonZheadersr   r(   z0Successfully sent conversation summary for call zAPI Response: Tz-Failed to send conversation summary for call zStatus Code: z
Response: z.Timeout sending conversation summary for call z7Connection error sending conversation summary for call z4Request error sending conversation summary for call z: Nz7Unexpected error sending conversation summary for call )r	   r   r   r=   r   r+   Z	isoformatr
   requestsZpostr   Zstatus_codetextr9   
exceptionsZTimeoutConnectionErrorZRequestExceptionr-   r8   )r   r   r   r   ZsummaryZpayloadZresponser<   r   r   r   send_conversation_summary   sT   


	
z4ConversationSummaryService.send_conversation_summaryc                 C   s   z+|j |j|j|jrtt |j  nd|jt|dg t|dg |j	|j
|jd
W S  ty^ } z'td|  t|ddt|ddt|d	ddt g g dd
W  Y d}~S d}~ww )z
        Extract summary data from a call session.
        
        Args:
            session: CallSession instance
            
        Returns:
            Dictionary with session data for summary
        r   r   r   )
r   r   r   r   r   r   r   conversation_countagent_iddidz'Error extracting session summary data: r   r   r   r   )r   r   r   r   r   r   r   rI   N)r   r   r   r   intr   r+   Ztotal_secondsgetattrrI   rJ   rK   r8   r   r9   )r   Zsessionr<   r   r   r   get_session_summary_data   s2   





z3ConversationSummaryService.get_session_summary_dataN)__name__
__module____qualname____doc__r   r   r-   r   r=   r   r6   boolrH   rN   r   r   r   r   r      s    
v">r   )rR   rD   rC   Zloggingr   typingr   r   r   r   Zconfigr   Z	getLoggerrO   r   r   Zconversation_summary_servicer   r   r   r   <module>   s    
  
