o
    †v•j3+  ã                   @   s   d dl Z d dlZd dlZ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 d dlmZ d dlmZ e e¡Zd"d
ededefdd„Z			d#dededB dee dedB dededB deeef fdd„Z	d$dededededB def
dd„Z	d%dedededefd d!„ZdS )&é    N)ÚdatetimeÚtimezone)ÚEmailMessage)ÚAny)Úsettings)Úget_conversation_by_session_id)Úget_messages_by_conversation_id)Úget_session_by_idFÚdt_valÚ	time_onlyÚreturnc                 C   s‚   | sdS t | tƒr zt |  dd¡¡} W n ty   |  Y S w t | tƒr=| jd u r1| jtjd�} |r8|  	d¡S |  	d¡S t| ƒS )NúN/AÚZz+00:00)Útzinfoz%H:%M:%S UTCz%Y-%m-%d %H:%M:%S UTC)
Ú
isinstanceÚstrr   ÚfromisoformatÚreplaceÚ	Exceptionr   r   ÚutcÚstrftime)r
   r   © r   ú;/web/html/dev/chatbot/backend/app/services/email_service.pyÚ_format_time_str   s   
ÿ



r   ÚvisitorÚsessionÚconversationÚmessagesÚ
agent_infoÚended_byÚended_atc                 C   s  |   dd¡}|   dd¡}|   d¡pd}|   d¡pd}	d}
d}|r4|  d¡p+|  d¡p+d	}
|  d
¡p2d}n|   d¡r@|   d¡}
d}t|   d¡pJ|   d¡ƒ}t|pTt tj¡ƒ}ddd|› �d|› �d|› �d|	› �d|
› �d|› �d|› �d|› �d|› �dddg}|s‰| d¡ nN|D ]K}t|  d¡dd�}|  d d!¡ ¡ }|d"v r¥d#}n|d$v r¶|
dkr³d%|
› d&�nd'}n|d(kr½d)}n| ¡ }|  d*d¡}| d+|› d,|› d-|› d.�¡ q‹d. 	|¡}d/d0d1d2|› d3�d4|› d3�d5|› d3�d6|	› d3�d7|
› d3�d8|› d3�d9|› d3�d:|› d3�d;|› d3�d<d=d>g}|�s| d?¡ n_|D ]\}t|  d¡dd�}|  d d!¡ ¡ }|d"v �r;d#}d@}dA}n|d$v �rR|
dk�rKd%|
› d&�nd'}dB}dC}nd)}dD}dE}|  d*d¡ 
d.dF¡}| dG|› dH|› dI|› dJ|› dK|› dL�¡ �q| dM¡ d 	|¡}||fS )Nz^
    Builds the formatted plain text and HTML email bodies for a chat session transcript.
    Ú	sessionIdÚUnknownÚsiteIdÚ	ipAddressÚcountryÚNoneÚnameÚagentIdzAssigned AgentÚemailr   ÚassignedAgentIdÚ	createdAtÚconnectedAtzChat Session Detailsz--------------------z- Session ID: z- Site ID: z- Visitor IP: z- Country: z- Assigned Agent: z- Agent Email: z- Chat Started At: z- Chat Ended At: z- Ended By: Ú zConversation Transcriptz-----------------------z"(No messages in this conversation)T)r   ÚroleÚunknown)Úuserr   ÚVisitor)ÚagentÚ	assistantzAgent (ú)ÚAgentÚsystemÚSystemÚcontentú[z] z:
Ú
zS<html><body style='font-family: Arial, sans-serif; line-height: 1.5; color: #333;'>z<h2>Chat Session Details</h2>z?<table style='border-collapse: collapse; margin-bottom: 20px;'>zP<tr><td style='padding: 4px 12px 4px 0; font-weight: bold;'>Session ID:</td><td>z
</td></tr>zM<tr><td style='padding: 4px 12px 4px 0; font-weight: bold;'>Site ID:</td><td>zP<tr><td style='padding: 4px 12px 4px 0; font-weight: bold;'>Visitor IP:</td><td>zM<tr><td style='padding: 4px 12px 4px 0; font-weight: bold;'>Country:</td><td>zT<tr><td style='padding: 4px 12px 4px 0; font-weight: bold;'>Assigned Agent:</td><td>zQ<tr><td style='padding: 4px 12px 4px 0; font-weight: bold;'>Agent Email:</td><td>zU<tr><td style='padding: 4px 12px 4px 0; font-weight: bold;'>Chat Started At:</td><td>zS<tr><td style='padding: 4px 12px 4px 0; font-weight: bold;'>Chat Ended At:</td><td>zN<tr><td style='padding: 4px 12px 4px 0; font-weight: bold;'>Ended By:</td><td>z</table>z <h2>Conversation Transcript</h2>zf<div style='background-color: #f8fafc; border: 1px solid #e2e8f0; border-radius: 8px; padding: 16px;'>zJ<p style='color: #64748b;'><em>(No messages in this conversation)</em></p>z#e0f2fez#38bdf8z#f1f5f9z#94a3b8z#fef3c7z#f59e0bz<br>z@<div style='margin-bottom: 12px; padding: 8px 12px; background: z; border-left: 3px solid zZ; border-radius: 4px;'><div style='font-size: 11px; color: #64748b; margin-bottom: 4px;'>[z
] <strong>z-</strong></div><div style='font-size: 13px;'>z</div></div>z</div></body></html>)Úgetr   r   Únowr   r   ÚappendÚlowerÚ
capitalizeÚjoinr   )r   r   r   r   r   r    Ú
session_idÚsite_idÚ
ip_addressr%   Ú
agent_nameÚagent_emailÚstarted_at_strÚended_at_strÚlinesÚmÚmsg_timer.   Úsender_labelr8   Ú	text_bodyÚ
html_linesÚbg_colorÚborder_colorÚ	html_bodyr   r   r   Úbuild_transcript_email_content!   s²   

ò 









ñ

ÿÿþÿ

rQ   Ú	recipientÚsubjectÚtext_contentÚhtml_contentc              
   C   sˆ  t jst d|› d| › d�¡ dS tƒ }||d< t j|d< | |d< | |¡ |r/|j|dd	� ztt jrat	j
t jt jd
d��}t jrLt jrL| t jt j¡ | |¡ W d  ƒ n1 s[w   Y  n4t	jt jt jd
d��"}t jrs| ¡  t jr�t jr�| t jt j¡ | |¡ W d  ƒ n1 s�w   Y  t d| › d|› d�¡ W dS  tyÃ } ztjd| › d|› �dd� W Y d}~dS d}~ww )z:Synchronous SMTP sending worker executed in a thread pool.z>[EMAIL] No SMTP host configured. Logged transcript email for 'z' to 'z'.TÚSubjectÚFromÚToÚhtml)Úsubtypeé
   )ÚtimeoutNz.[EMAIL] Successfully sent transcript email to z (r4   z [EMAIL] Failed to send email to z via SMTP: ©Úexc_infoF)r   Ú	smtp_hostÚloggerÚinfor   Úsmtp_from_emailÚset_contentÚadd_alternativeÚsmtp_use_sslÚsmtplibÚSMTP_SSLÚ	smtp_portÚ	smtp_userÚsmtp_passwordÚloginÚsend_messageÚSMTPÚsmtp_use_tlsÚstarttlsr   Úerror)rR   rS   rT   rU   ÚmsgÚserverÚer   r   r   Ú_send_smtp_sync˜   sD   ÿ

ý€û€þrt   ÚdbrA   c              
   Ã   sÈ  �| du rdS z¼t | |ƒI dH }|st d|› �¡ W dS t| |ƒI dH }|r+|d nd}|r@| d¡r@t d|› d�¡ W dS | d¡rQt d	|› d�¡ W dS g }|r]t| |ƒI dH }d}| d
¡}|rr| d  d|i¡I dH }d|› �}	tj	p{d}
t
 tj¡}t||||||d�\}}tjt|
|	||d�I dH }|r¯| d  d|idd|dœi¡I dH  | d  d|idd|dœi¡I dH  |W S  tyã } ztjd|› d|› �dd� W Y d}~dS d}~ww )aE  
    Fetches the complete session conversation history and metadata from MongoDB,
    generates the formatted transcript, and emails it to the configured admin email.
    
    Prevents duplicate emails if already sent for this conversation.
    Gracefully catches failures without interrupting the chat termination flow.
    NFz0[EMAIL] Session not found for transcript email: ÚconversationIdÚtranscriptEmailedz[EMAIL] Conversation z0 transcript already emailed. Skipping duplicate.Tz[EMAIL] Session r*   Úagentsr(   u   Chat Conversation â€” zalok.chaudhary2001@gmail.com)r   r   r   r   r   r    )rR   rS   rT   rU   Úconversationsz$set)rw   ÚtranscriptEmailedAtÚsessionsr!   zA[EMAIL] Unexpected error generating/sending transcript email for z: r]   )r	   r`   Úwarningr   r;   ra   r   Úfind_oner   Úadmin_notification_emailr   r<   r   r   rQ   ÚasyncioÚ	to_threadrt   Ú
update_oner   rp   )ru   rA   r   r   ÚconvÚconv_idr   r   Úassigned_agent_idrS   rR   r    rL   rP   Úsent_successrs   r   r   r   Ú"send_conversation_transcript_emailÂ   sp   €




ú
û	
þ
þ€þr†   )F)Nr   N)N)r   )r   Úloggingrf   r   r   Úemail.messager   Útypingr   Ú
app.configr   Ú(app.repositories.conversation_repositoryr   Ú#app.repositories.message_repositoryr   Ú#app.repositories.session_repositoryr	   Ú	getLoggerÚ__name__r`   Úboolr   r   ÚdictÚlistÚtuplerQ   rt   r†   r   r   r   r   Ú<module>   sh    
úÿþýüûú

ù{üÿþýü
û-ýÿþýü