o
    d6i                  
   @   s   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 e e	Z
ddededeeeef  fdd	Zddededeeeef  fddZdS )    N)datetime)DictListAny   phone_numberlimitreturnc              
      s  zt d}t d}t d}t d}t||||gs&td g W S d|  } | d| d|  }||d	}d
d| i}tjdd4 I dH }	|	j|||dI dH }
|
  |
	 }W d  I dH  n1 I dH sow   Y  g }|di }t
|tr|dg ng }|D ]/}|ddkrq|dd}|dd}|d|dd}|r||rdnd||d q|  tdt| d |W S  tjy } ztdt|j  g W  Y d}~S d}~w ty } ztd t|j  g W  Y d}~S d}~ww )!a  
    Load chat history from WATI API for a specific phone number.
    
    Args:
        phone_number: User's phone number (without country code)
        limit: Number of messages to fetch (default: 5)
        
    Returns:
        List of chat messages in chronological order with format:
        [{"type": "user" or "assistant", "message": "text", "timestamp": "iso_timestamp"}]
    WATI_URLWATI_TENANT_IDWATI_CHANNEL_PHONE_NUMBERWATI_BEARER_TOKENz9WATI credentials not configured. Returning empty history.91/z/api/v1/getMessages/)channelPhoneNumberpageSizeAuthorizationzBearer g      $@)timeoutN)paramsheadersmessagesitems	eventTypemessageownerFtext created	timestamp	assistantuser)typer   r   zLoaded z messages from WATIz+HTTP error loading chat history from WATI: z&Error loading chat history from WATI: )osgetenvallloggerwarninghttpxAsyncClientgetraise_for_statusjson
isinstancedictappendreversedebuglen	HTTPErrorerrorr!   __name__	Exception)r   r   wati_url	tenant_idchannel_phonebearer_tokenurlr   r   clientresponsedatachat_historymessages_datar   msgis_ownermessage_textr   e rD   @/var/www/html/karishye-ai-python/app/utils/conversation_utils.pyload_chat_history   sb   







(
rF      c                 C   sJ   ddl }z| }W n ty   | }|| Y nw |t| |S )z
    Get recent chat history for a phone number from WATI.
    This is a synchronous wrapper - use load_chat_history directly in async contexts.
    r   N)asyncioget_event_loopRuntimeErrornew_event_loopset_event_looprun_until_completerF   )r   r   rH   looprD   rD   rE   get_recent_chat_history^   s   rO   )r   )rG   )loggingr"   r'   r   typingr   r   r   	getLoggerr4   r%   strintrF   rO   rD   rD   rD   rE   <module>   s    
$(S