U
    Shs                  	   @   s  d Z ddlZddlZddl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mZmZmZ ddlZddlZddlZdd	lmZmZmZmZmZmZmZmZ eeZ G d
d dZ!e! Z"de#e#eee#ef  ee$ eee#e#f  eee#  e%dddZ&de#e#e#ee' ee ee e%dddZ(de#e#e#eee#ef  e%dddZ)e#e#ee%dddZ*e%dddZ+dS )z
Email notification service for critical errors and system failures.
This module provides automatic email notifications when critical errors occur.
    N)MIMEText)MIMEMultipart)MIMEBase)encoders)datetime)DictAnyOptionalList)EMAIL_SMTP_SERVEREMAIL_SMTP_PORTEMAIL_USERNAMEEMAIL_PASSWORDEMAIL_RECIPIENTSEMAIL_FROM_ADDRESSEMAIL_USE_TLSEMAIL_USE_SSLc                	   @   s  e Zd ZdZdd Zdd Zd%eeeeee	f  ee
 eeeef  eee  eddd	Zd&eeeee ee ee ed
ddZd'eeeeeee	f  edddZd(eeeeee	f  ee
 eeeef  edddZd)eeeee ee ee ed
ddZd*eeeeeee	f  edddZd+eeeee edddZeeeedddZeeeedd d!Zed"d#d$ZdS ),EmailNotifierz@Email notification service for critical errors and system alertsc                 C   s<   t | _t| _t| _t| _t| _	t
| _t| _t| _|   dS )z5Initialize the email notifier with SMTP configurationN)r   smtp_serverr   	smtp_portr   usernamer   passwordr   
recipientsr   from_addressr   use_tlsr   use_ssl_validate_config)self r   A/var/www/html/testcasegenerator.evdpl.com/utils/email_notifier.py__init__   s    zEmailNotifier.__init__c                 C   s   d| j fd| jfd| jfd| jfd| jfd| jfg}g }|D ]\}}|s<|| q<|rvtdd	|  d	| _
nd
| _
td dS )zValidate email configurationZSMTP_SERVERZ	SMTP_PORTUSERNAMEZPASSWORDZ
RECIPIENTSZFROM_ADDRESSz5Email notification disabled - missing configuration: , FTz3Email notification service initialized successfullyN)r   r   r   r   r   r   appendloggerwarningjoinenabledinfo)r   Zrequired_configsZmissing_configsnamevaluer   r   r   r   *   s     	zEmailNotifier._validate_configN
error_typeerror_messagecontext	exceptionuser_contextr   returnc           
   
   C   s   | j std dS z2d| d}| |||||}| j||d|dW S  tk
r }	 ztdt|	  W Y dS d}	~	X Y nX dS )	a  
        Send critical error notification email
        
        Args:
            error_type: Type of error (API_FAILURE, SYSTEM_ERROR, etc.)
            error_message: Error message
            context: Additional context data
            exception: Exception object if available
            user_context: User information if available
            
        Returns:
            bool: True if email sent successfully, False otherwise
        zCEmail notifications disabled - skipping critical error notificationFu   🚨 CRITICAL ERROR ALERT -  - AI Test Case GeneratorTis_htmlr   z,Failed to send critical error notification: N)r'   r$   r%   _create_error_email_body_send_email	Exceptionerrorstr)
r   r,   r-   r.   r/   r0   r   subjectbodyer   r   r    send_critical_error_notificationA   s     
    z.EmailNotifier.send_critical_error_notificationapi_nameendpointr-   status_coderesponse_datarequest_datar1   c           
   
   C   s   | j std dS z2d| d}| ||||||}| j||ddW S  tk
r }	 ztdt|	  W Y dS d}	~	X Y nX dS )	a  
        Send API failure notification email
        
        Args:
            api_name: Name of the API (OpenAI, Jira, Azure, etc.)
            endpoint: API endpoint that failed
            error_message: Error message
            status_code: HTTP status code if available
            response_data: API response data if available
            request_data: Request data if available
            
        Returns:
            bool: True if email sent successfully, False otherwise
        z@Email notifications disabled - skipping API failure notificationFu   ⚠️ API FAILURE - r2   Tr4   z)Failed to send API failure notification: N)r'   r$   r%   _create_api_failure_email_bodyr6   r7   r8   r9   )
r   r?   r@   r-   rA   rB   rC   r:   r;   r<   r   r   r   send_api_failure_notificationf   s"    
     z+EmailNotifier.send_api_failure_notificationWARNING
alert_typemessageseverityr.   r1   c           	   
   C   s   | j std dS zN|dkr"dn|dkr.dnd}| d| d	}| ||||}| j||d
dW S  tk
r } ztdt|  W Y dS d}~X Y nX dS )a{  
        Send system alert notification
        
        Args:
            alert_type: Type of alert (PERFORMANCE, SECURITY, etc.)
            message: Alert message
            severity: Alert severity (INFO, WARNING, CRITICAL)
            context: Additional context data
            
        Returns:
            bool: True if email sent successfully, False otherwise
        z4Email notifications disabled - skipping system alertFCRITICAL   🔴rG      🟡   🔵z SYSTEM ALERT - r2   TrD   zFailed to send system alert: N)r'   r$   r%   _create_system_alert_email_bodyr6   r7   r8   r9   )	r   rI   rJ   rK   r.   emojir:   r;   r<   r   r   r   send_system_alert   s    
zEmailNotifier.send_system_alert)r,   r-   r.   r/   r0   r1   c                 C   s   t  d}d}|rFzdtt|||j}W n   d}Y nX d}|rddtj	|dd d}d}	|rddd	d
 |
 D  d}	d}
|rd| d}
d| d| d| d|	 d| d|
 d}|S )z*Create HTML email body for critical errors%Y-%m-%d %H:%M:%S UTC zUnable to extract traceback   
            <h3>📋 Additional Context:</h3>
            <pre style="background-color: #f5f5f5; padding: 10px; border-radius: 5px; overflow-x: auto;">   indent</pre>
            uN   
            <h3>👤 User Information:</h3>
            <ul>
                c                 S   s"   g | ]\}}d | d| dqS )z<li><strong>z:</strong> z</li>r   ).0kvr   r   r   
<listcomp>   s     z:EmailNotifier._create_error_email_body.<locals>.<listcomp>z
            </ul>
            u   
            <h3>🔍 Stack Trace:</h3>
            <pre style="background-color: #f5f5f5; padding: 10px; border-radius: 5px; overflow-x: auto; font-size: 12px;">u  
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <title>Critical Error Alert</title>
        </head>
        <body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333;">
            <div style="max-width: 800px; margin: 0 auto; padding: 20px;">
                <div style="background-color: #dc3545; color: white; padding: 20px; border-radius: 10px; margin-bottom: 20px;">
                    <h1 style="margin: 0; font-size: 24px;">🚨 CRITICAL ERROR ALERT</h1>
                    <p style="margin: 10px 0 0 0; font-size: 16px;">AI Test Case Generator System</p>
                </div>
                
                <div style="background-color: #f8f9fa; padding: 20px; border-radius: 10px; margin-bottom: 20px;">
                    <h2 style="color: #dc3545; margin-top: 0;">Error Details</h2>
                    <p><strong>⏰ Timestamp:</strong> u>   </p>
                    <p><strong>🔧 Error Type:</strong> u  </p>
                    <p><strong>📝 Error Message:</strong></p>
                    <div style="background-color: #fff; padding: 15px; border-left: 4px solid #dc3545; margin: 10px 0;">
                        <code style="color: #dc3545; font-size: 14px;">[</code>
                    </div>
                </div>
                
                
                u  
                
                <div style="background-color: #e9ecef; padding: 15px; border-radius: 5px; margin-top: 20px;">
                    <h3>🔧 Recommended Actions:</h3>
                    <ul>
                        <li>Check the application logs for more details</li>
                        <li>Verify system resources and connectivity</li>
                        <li>Review recent deployments or configuration changes</li>
                        <li>Monitor system performance and user impact</li>
                    </ul>
                </div>
                
                <div style="text-align: center; margin-top: 30px; padding-top: 20px; border-top: 1px solid #dee2e6;">
                    <p style="color: #6c757d; font-size: 12px;">
                        This is an automated alert from the AI Test Case Generator monitoring system.
                    </p>
                </div>
            </div>
        </body>
        </html>
        )r   nowstrftimer&   	tracebackformat_exceptiontype__traceback__jsondumpsitems)r   r,   r-   r.   r/   r0   	timestampZtraceback_infocontext_htmlZ	user_htmlZtraceback_html	html_bodyr   r   r   r5      sP      

0z&EmailNotifier._create_error_email_bodyc                 C   s   t  d}d}|r,dtj|dd d}d}	|rJdtj|dd d}	d| d	| d
| d|rnd| dnd d| d|	 d| d}
|
S )z'Create HTML email body for API failuresrS   rT   u   
            <h3>📤 API Response:</h3>
            <pre style="background-color: #f5f5f5; padding: 10px; border-radius: 5px; overflow-x: auto;">rV   rW   rY   u   
            <h3>📥 Request Data:</h3>
            <pre style="background-color: #f5f5f5; padding: 10px; border-radius: 5px; overflow-x: auto;">u  
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <title>API Failure Alert</title>
        </head>
        <body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333;">
            <div style="max-width: 800px; margin: 0 auto; padding: 20px;">
                <div style="background-color: #fd7e14; color: white; padding: 20px; border-radius: 10px; margin-bottom: 20px;">
                    <h1 style="margin: 0; font-size: 24px;">⚠️ API FAILURE ALERT</h1>
                    <p style="margin: 10px 0 0 0; font-size: 16px;">AI Test Case Generator System</p>
                </div>
                
                <div style="background-color: #f8f9fa; padding: 20px; border-radius: 10px; margin-bottom: 20px;">
                    <h2 style="color: #fd7e14; margin-top: 0;">API Failure Details</h2>
                    <p><strong>⏰ Timestamp:</strong> u<   </p>
                    <p><strong>🔌 API Name:</strong> uB   </p>
                    <p><strong>🌐 Endpoint:</strong> <code>z </code></p>
                    uD   <p><strong>📊 Status Code:</strong> <span style="color: #dc3545;">z</span></p>u  
                    <p><strong>📝 Error Message:</strong></p>
                    <div style="background-color: #fff; padding: 15px; border-left: 4px solid #fd7e14; margin: 10px 0;">
                        <code style="color: #dc3545; font-size: 14px;">r^   r_   u  
                
                <div style="background-color: #e9ecef; padding: 15px; border-radius: 5px; margin-top: 20px;">
                    <h3>🔧 Recommended Actions:</h3>
                    <ul>
                        <li>Check API service status and connectivity</li>
                        <li>Verify API credentials and authentication</li>
                        <li>Review API rate limits and quotas</li>
                        <li>Check for API endpoint changes or deprecations</li>
                        <li>Monitor API response times and error rates</li>
                    </ul>
                </div>
                
                <div style="text-align: center; margin-top: 30px; padding-top: 20px; border-top: 1px solid #dee2e6;">
                    <p style="color: #6c757d; font-size: 12px;">
                        This is an automated alert from the AI Test Case Generator monitoring system.
                    </p>
                </div>
            </div>
        </body>
        </html>
        r   r`   ra   rf   rg   )r   r?   r@   r-   rA   rB   rC   ri   Zresponse_htmlZrequest_htmlrk   r   r   r   rE   	  s6    2z,EmailNotifier._create_api_failure_email_bodyc           
      C   s   t  d}|dkrdn|dkr&dnd}|dkr6dn|dkrBdnd	}d
}|rddtj|dd d}d| d| d| d| d| d| d| d| d| d| d| d}	|	S )z(Create HTML email body for system alertsrS   rL   z#dc3545rG   z#fd7e14z#17a2b8rM   rN   rO   rT   rU   rV   rW   rY   aa  
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <title>System Alert</title>
        </head>
        <body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333;">
            <div style="max-width: 800px; margin: 0 auto; padding: 20px;">
                <div style="background-color: z; color: white; padding: 20px; border-radius: 10px; margin-bottom: 20px;">
                    <h1 style="margin: 0; font-size: 24px;">a9   SYSTEM ALERT</h1>
                    <p style="margin: 10px 0 0 0; font-size: 16px;">AI Test Case Generator System</p>
                </div>
                
                <div style="background-color: #f8f9fa; padding: 20px; border-radius: 10px; margin-bottom: 20px;">
                    <h2 style="color: u\   ; margin-top: 0;">Alert Details</h2>
                    <p><strong>⏰ Timestamp:</strong> u>   </p>
                    <p><strong>🚨 Alert Type:</strong> uO   </p>
                    <p><strong>⚡ Severity:</strong> <span style="color: z; font-weight: bold;">u   </span></p>
                    <p><strong>📝 Message:</strong></p>
                    <div style="background-color: #fff; padding: 15px; border-left: 4px solid zH; margin: 10px 0;">
                        <p style="margin: 0; color: z; font-size: 14px;">zX</p>
                    </div>
                </div>
                
                u  
                
                <div style="background-color: #e9ecef; padding: 15px; border-radius: 5px; margin-top: 20px;">
                    <h3>🔧 Recommended Actions:</h3>
                    <ul>
                        <li>Review system logs and monitoring dashboards</li>
                        <li>Check system resources and performance metrics</li>
                        <li>Verify system configuration and dependencies</li>
                        <li>Monitor for any user impact or service degradation</li>
                    </ul>
                </div>
                
                <div style="text-align: center; margin-top: 30px; padding-top: 20px; border-top: 1px solid #dee2e6;">
                    <p style="color: #6c757d; font-size: 12px;">
                        This is an automated alert from the AI Test Case Generator monitoring system.
                    </p>
                </div>
            </div>
        </body>
        </html>
        rl   )
r   rI   rJ   rK   r.   ri   colorrQ   rj   rk   r   r   r   rP   U  s@    	
				/z-EmailNotifier._create_system_alert_email_bodyT)r:   r;   r4   r   r1   c           
   
   C   s4  z|r
|n| j }|s$td W dS td}||d< | j|d< d||d< |rb|t|d n|t|d	 | jrt	
 }tj| j| j|d
}nt| j| j}| jr|  || j| j || |  tdd|  W dS  tk
r. }	 ztdt|	  W Y dS d}	~	X Y nX dS )ai  
        Send email using SMTP
        
        Args:
            subject: Email subject
            body: Email body
            is_html: Whether the body is HTML format
            recipients: List of email recipients (defaults to configured recipients)
            
        Returns:
            bool: True if email sent successfully, False otherwise
        zNo email recipients specifiedFalternativeZSubjectZFromr"   ZTohtmlplain)r.   zEmail sent successfully to TzFailed to send email: N)r   r$   r8   r   r   r&   attachr   r   sslcreate_default_contextsmtplibZSMTP_SSLr   r   ZSMTPr   Zstarttlsloginr   r   send_messagequitr(   r7   r9   )
r   r:   r;   r4   r   Zemail_recipientsmsgr.   serverr<   r   r   r   r6     s4    


zEmailNotifier._send_emailemailreset_token
expires_atr1   c           
   
   C   s   | j std dS zLddlm} d}| d| }|d}| |||}| j||d|gd	W S  tk
r }	 zt	d
t
|	  W Y dS d}	~	X Y nX dS )a'  
        Send password reset email
        
        Args:
            email: User's email address
            reset_token: Password reset token
            expires_at: Token expiration time
            
        Returns:
            bool: True if email sent successfully, False otherwise
        z?Email notifications disabled - cannot send password reset emailFr   )BASE_URLu4   🔐 Password Reset Request - AI Test Case Generatorz/reset-password-confirm?token=z%B %d, %Y at %I:%M %p UTCTr3   z%Failed to send password reset email: N)r'   r$   r%   config.settingsr~   ra   !_create_password_reset_email_bodyr6   r7   r8   r9   )
r   r{   r|   r}   r~   r:   
reset_linkexpires_strr;   r<   r   r   r   send_password_reset_email  s    

z'EmailNotifier.send_password_reset_email)r{   r   r   r1   c                 C   s6   t  d}d| d| d| d| d| d}|S )z)Create HTML email body for password resetrS   u  
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <title>Password Reset Request</title>
        </head>
        <body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333;">
            <div style="max-width: 600px; margin: 0 auto; padding: 20px;">
                <div style="background-color: #007bff; color: white; padding: 20px; border-radius: 10px; margin-bottom: 20px;">
                    <h1 style="margin: 0; font-size: 24px;">🔐 Password Reset Request</h1>
                    <p style="margin: 10px 0 0 0; font-size: 16px;">AI Test Case Generator</p>
                </div>
                
                <div style="background-color: #f8f9fa; padding: 20px; border-radius: 10px; margin-bottom: 20px;">
                    <h2 style="color: #007bff; margin-top: 0;">Reset Your Password</h2>
                    <p>Hello,</p>
                    <p>We received a request to reset your password for your AI Test Case Generator account associated with <strong>aC  </strong>.</p>
                    
                    <div style="background-color: #fff; padding: 20px; border-radius: 5px; margin: 20px 0; text-align: center;">
                        <p style="margin: 0 0 15px 0; font-weight: bold;">Click the button below to reset your password:</p>
                        <a href="a[  " style="display: inline-block; background-color: #007bff; color: white; padding: 12px 30px; text-decoration: none; border-radius: 5px; font-weight: bold; font-size: 16px;">
                            Reset My Password
                        </a>
                    </div>
                    
                    <p style="margin: 20px 0 10px 0;"><strong>Or copy and paste this link into your browser:</strong></p>
                    <div style="background-color: #e9ecef; padding: 10px; border-radius: 5px; word-break: break-all; font-family: monospace; font-size: 14px;">
                        u  
                    </div>
                </div>
                
                <div style="background-color: #fff3cd; border: 1px solid #ffeaa7; padding: 15px; border-radius: 5px; margin-bottom: 20px;">
                    <h3 style="color: #856404; margin-top: 0;">⚠️ Important Security Information</h3>
                    <ul style="color: #856404; margin: 0;">
                        <li>This link will expire on <strong>u  </strong></li>
                        <li>The link can only be used once</li>
                        <li>If you didn't request this password reset, please ignore this email</li>
                        <li>Your password will remain unchanged until you click the link above</li>
                    </ul>
                </div>
                
                <div style="background-color: #e9ecef; padding: 15px; border-radius: 5px; margin-bottom: 20px;">
                    <h3 style="margin-top: 0;">🔒 Security Tips</h3>
                    <ul style="margin: 0;">
                        <li>Choose a strong, unique password</li>
                        <li>Don't share your password with anyone</li>
                        <li>Log out of your account when using shared computers</li>
                        <li>Contact support if you notice any suspicious activity</li>
                    </ul>
                </div>
                
                <div style="text-align: center; margin-top: 30px; padding-top: 20px; border-top: 1px solid #dee2e6;">
                    <p style="color: #6c757d; font-size: 12px; margin: 0;">
                        This email was sent on z<br>
                        If you have any questions, please contact our support team.
                    </p>
                </div>
            </div>
        </body>
        </html>
        )r   r`   ra   )r   r{   r   r   ri   rk   r   r   r   r     s    #6?z/EmailNotifier._create_password_reset_email_bodyr1   c              
   C   s   | j std dS z,d}dt d d}| j||ddW S  tk
r| } ztd	t	|  W Y dS d
}~X Y nX d
S )z
        Test email configuration by sending a test email
        
        Returns:
            bool: True if test email sent successfully, False otherwise
        z8Email notifications disabled - cannot test configurationFu6   🧪 Email Configuration Test - AI Test Case Generatoru  
            <!DOCTYPE html>
            <html>
            <head>
                <meta charset="UTF-8">
                <title>Email Test</title>
            </head>
            <body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333;">
                <div style="max-width: 600px; margin: 0 auto; padding: 20px;">
                    <div style="background-color: #28a745; color: white; padding: 20px; border-radius: 10px; text-align: center;">
                        <h1 style="margin: 0;">✅ Email Configuration Test Successful</h1>
                    </div>
                    <div style="background-color: #f8f9fa; padding: 20px; border-radius: 10px; margin-top: 20px;">
                        <p><strong>Timestamp:</strong> rS   aq  </p>
                        <p><strong>Service:</strong> AI Test Case Generator</p>
                        <p><strong>Status:</strong> Email notifications are working correctly</p>
                    </div>
                    <div style="text-align: center; margin-top: 30px; padding-top: 20px; border-top: 1px solid #dee2e6;">
                        <p style="color: #6c757d; font-size: 12px;">
                            This is a test email to verify email notification configuration.
                        </p>
                    </div>
                </div>
            </body>
            </html>
            TrD   zFailed to send test email: N)
r'   r$   r%   r   r`   ra   r6   r7   r8   r9   )r   r:   r;   r<   r   r   r   test_email_configuration9  s    
z&EmailNotifier.test_email_configuration)NNNN)NNN)rG   N)NNN)NNN)N)TN)__name__
__module____qualname____doc__r    r   r9   r	   r   r   r7   r
   boolr=   intrF   rR   r5   rE   rP   r6   r   r   r   r   r   r   r   r   r      sx       
 &     &     !    _     M   C6%Fr   r+   c                 C   s   t | |||||S )z&Send critical error notification email)email_notifierr=   )r,   r-   r.   r/   r0   r   r   r   r   r=   k  s         r=   r>   c                 C   s   t | |||||S )z#Send API failure notification email)r   rF   )r?   r@   r-   rA   rB   rC   r   r   r   rF   u  s         rF   rG   rH   c                 C   s   t | |||S )z$Send system alert notification email)r   rR   )rI   rJ   rK   r.   r   r   r   rR   ~  s    rR   rz   c                 C   s   t | ||S )zSend password reset email)r   r   )r{   r|   r}   r   r   r   r     s    r   r   c                   C   s   t  S )zTest email configuration)r   r   r   r   r   r   r     s    r   )NNNN)NNN)rG   N),r   rt   rr   loggingZemail.mime.textr   Zemail.mime.multipartr   Zemail.mime.baser   r{   r   r   typingr   r   r	   r
   osrb   rf   r   r   r   r   r   r   r   r   r   	getLoggerr   r$   r   r   r9   r7   r   r=   r   rF   rR   r   r   r   r   r   r   <module>   sd   (
    S    
      
     