o
    dio:                     @   s   d dl Z d dlZd dlZd dlZd dlZd dlmZ d dlZd dlZd dl	m
Z
 ejejd eeZdZdZdZdZd	Zd
ZdZdZdZdZdZdd Zdd Zdd Zdd Zdd Zd"ddZ dd Z!d"ddZ"d d! Z#dS )#    N)MIMEText)get_db_connection)levelAKIAUWPMKLMSD556YYR5(yOku358ASGrJPRdTWYfyKnUAVH6QN1qlR2fQO7KDz
eu-north-1zamazon.nova-lite-v1:0z7https://rengage.mcube.com/api/wpbox/sendtemplatemessage0DGw6K3278c1e4y9aF0veYYt5uC90tk7wEVHDJk4G9270b2c2z"email-smtp.us-east-1.amazonaws.comi  znoreply@mcubemail.comAKIAUJVLLICOLBGNBZHVz,BNy8uBvRElGITJRVc/s6HWi9YEyj0v2DK1dhdQABKRkZc                   C   s   t jdtttdS )zInitialize AWS Bedrock clientzbedrock-runtime)region_nameaws_access_key_idaws_secret_access_key)boto3client
AWS_REGIONAWS_ACCESS_KEY_IDAWS_SECRET_ACCESS_KEY r   r   :/home/aiteam/pcaa-dev/post call analysis/message_helper.pyget_bedrock_client/   s   r   c              
   C   s   z[t  }|jttdddigdddd|  digdgddd	d
d}t|d  }|d d d d d  }t	d|tj
}|rO|d }nd}td|  |W S  tyx } ztdt|  W Y d}~dS d}~ww )z1Detect intent from call summary using AWS Bedrockusertextz]You are an intent detection system. From the following call summary, extract the main intent.)rolecontentzCall Summary: z}

Give the intent as one of these categories:
[Product Inquiry, Complaint, Support Request, Billing, Brochure Request, Other]r      )temperature	maxTokens)messagesinferenceConfig)modelIdbodyr   outputmessager   zlProduct Inquiry|Complaint|Support Request|Billing|Brochure Request|General Inquiry|Pricing|Schedule_FollowupotherzDetected Intent: zError detecting intent: N)r   invoke_modelMODEL_IDjsondumpsloadsreadstripresearch
IGNORECASEgrouplowerloggerinfo	Exceptionerrorstr)summary_textr   responseresultintent_detected_rawmatchintent_detecteder   r   r   detect_intent8   sD   	r:   c                 C   sD   t d| }t d| }|r|dnd}|r|dnd}||fS )z)Extract email and phone from summary textz[\w\.-]+@[\w\.-]+z\+?\d[\d -]{8,}\dr   N)r)   r*   r,   )r3   email_matchphone_match	emp_email	emp_phoner   r   r   extract_contact_infoe   s
   r?   c                 C   sZ   | sdS g d}|    }||v rdS td| sdS tdd| }t|dk r+dS dS )z?Check if phone number is valid (not 'Not available' or similar)F	znot availablez	not foundzn/ananoneunavailablemissingunknownznot providedz\dz\D    T)r-   r(   r)   r*   sublen)phonenot_available_patternsphone_lowerdigits_onlyr   r   r   is_valid_phoneo   s   rN   c                 C   s@   | sdS g d}|    }||v rdS d}t|| sdS dS )z8Check if email is valid (not 'Not available' or similar)Fr@   z0^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$T)r-   r(   r)   r7   )emailrK   email_loweremail_patternr   r   r   is_valid_email   s   rR   c              
   C   s   |   } |rd| dnd}d| ddd| ddd	| d
dd| ddd| ddd| ddd| ddd| ddd}|| d| dd}|d |d fS )z/Generate email subject and body based on intentzDear ,zDear Customer,z$Thank You for Your Interest in MCUBEz

Thank you for reaching out to us regarding our products. 
We value your interest and our team will share detailed information with you soon.



Best Regards,
MCUBE Team)subjectr   zWe Acknowledge Your Concernz

We're sorry to hear about the issue you faced. Please be assured that our support team is reviewing your concern and will provide an update shortly.



Sincerely,
MCUBE SupportzSupport Request Acknowledgedz

We have received your request for support. Our technical team will reach out shortly to assist you.



Regards,
MCUBE SupportzBilling Assistancez

Thank you for contacting us about billing. Our accounts team will get in touch with you soon with the required details.



Best Regards,
MCUBE Billing TeamzYour Requested Brochurez

Thank you for requesting our brochure. Please find attached our latest brochure with detailed information about our services.



Regards,
MCUBE TeamzWe Received Your Inquiryz

Thank you for reaching out to us. Our team has received your inquiry and will respond with the required information shortly.



Best Regards,
MCUBE TeamzPricing Information Requestz

We have received your request regarding pricing details. Our sales team will provide you with the relevant information shortly.



Best Regards,
MCUBE Sales TeamzFollow-Up Scheduledz

We have scheduled a follow-up call/meeting as per your request. Our representative will reach out to you on the agreed date and time.



Best Regards,
MCUBE Team)product inquiry	complaintzsupport requestbillingzbrochure requestzgeneral inquirypricingschedule_followupzThank You for Contacting MCUBEz

Thank you for connecting with us. Our team has received your request and will get in touch with you shortly.



Best Regards,
MCUBE TeamrT   r   )r-   get)intentsummarycustomer_namegreeting	templatestemplater   r   r   generate_email_body   s@   \ra   c              
   C   s  zyt d|  d|  dddd}||d}t d|  | |dd	d
digd}ddt d}t dt  t d|  tjt||dd}t d|j  t d|j  |jdkrnt d|   W dS t 	d|j  W dS  tj
jy   t 	d|   Y dS  tj
jy } zt 	dt|  W Y d}~dS d}~w ty } zt 	dt|  W Y d}~dS d}~ww ) z%Send WhatsApp message based on intentzStarting WhatsApp send to z with intent: voice_camplaintvoice_queryintent_general_template)rV   rU   r!   zUsing template: en_US91typer   )rJ   template_nametemplate_languagecountry_code
componentszapplication/jsonzBearer )zContent-TypeAuthorizationzSending WhatsApp request to: z	Payload:    )r$   headerstimeoutzWhatsApp API response status: zWhatsApp API response:    u   ✅ WhatsApp sent to zWhatsApp sent successfullyu   ❌ WhatsApp failed: zWhatsApp send failedu   ❌ WhatsApp API timeout for zWhatsApp send timeoutu    ❌ WhatsApp API request error: Nu   ❌ Error sending WhatsApp: )r.   r/   rZ   WHATSAPP_API_TOKENWHATSAPP_API_URLrequestspoststatus_coder   r1   
exceptionsTimeoutRequestExceptionr2   r0   )rJ   r[   r_   rh   payloadrn   r4   r9   r   r   r   send_whatsapp_message  sR   
rz   c           	   
   C   s   z<t |||\}}t|}||d< t|d< | |d< ttt}|tt	 |
t| |  |  td|   W dS  tyY } ztdt|  W Y d}~dS d}~ww )	z"Send email message based on intentSubjectFromTou   ✅ Email sent to zEmail sent successfullyu   ❌ Error sending email: NzEmail send failed)ra   r   SENDER_EMAILsmtplibSMTP_SSLSMTP_SERVER	SMTP_PORTloginSMTP_USERNAMESMTP_PASSWORDsendmail	as_stringquitr.   r/   r0   r1   r2   )	rO   r[   r\   r]   rT   r   msgserverr9   r   r   r   send_email_messageI  s"   r   c              
   C   sl  zt d|  d|  t }| }| d}|d| d| f | }|s=t d|   |  |  W dS |\}}}d\}	}
}|rz$t	|}|
d	}	|
d
}
|
d}t d| d|
 d|	  W n' tjy } zt d|  t|\}	}
W Y d}~nd}~ww t|\}	}
t|
}t|	}|s|st d|  d|
 d|	 d d}n8t|}|rt d|
  t|
|}t d|  n|rt d|	  t|	|||}t d|  nd}|d| d|| f |  |  |  t d|   d|fW S  ty5 } zt d|  d t|  d!t|fW  Y d}~S d}~ww )"z
    Main function to process call and send appropriate message
    
    Args:
        call_id: Call ID to process
        bid: Business ID for dynamic table naming
    z Processing message for call_id: z, bid: _callsz.SELECT callid, summary, customer_details FROM z! WHERE callid = %s AND status = 2zNo summary found for call_id: )FzNo summary found)NNNrO   rJ   namezCustomer details parsed: Name=z, Phone=z, Email=z'Failed to parse customer_details JSON: Nz(No valid email/phone found for call_id: z
. Phone: 'z', Email: ''z"No valid contact information foundz!Sending WhatsApp to valid phone: zWhatsApp send result: z Sending email to valid address: zEmail send result: z!No valid contact method availablezUPDATE z/ SET status = 3, remarks = %s WHERE callid = %su0   ✅ Message processed successfully for call_id: Tu)   ❌ Error processing message for call_id z: F)r.   r/   r   cursorexecutefetchonewarningcloser$   r&   rZ   JSONDecodeErrorr?   rN   rR   r:   rz   r   commitr0   r1   r2   )call_idbidconnr   calls_tablerowcall_id_from_dbr3   customer_details_jsonr=   r>   r]   customer_detailsr9   valid_phonevalid_emailremarksr8   r   r   r   send_message^  sp   






 


r   )N)$r   r$   pymysqlr)   r   email.mime.textr   rs   logging	db_configr   basicConfigINFO	getLogger__name__r.   r   r   r   r#   rr   rq   r   r   r~   r   r   r   r:   r?   rN   rR   ra   rz   r   r   r   r   r   r   <module>   s>   
	-

q
9