U
    hG                     @   s  d Z ddlZddlmZmZmZ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 dd	lmZmZ ed
Zeddddd$eedddZeddddedddZedd Zedd Zedd Zedd Zeeeeef dd d!Zed"d# ZdS )%z
Celery Tasks for Notification Processing

This module contains Celery tasks for handling notification delivery,
retry logic, and maintenance operations for the notification system.
    N)OptionalDictAnyList)shared_task)timezone)settings   )NotificationNotificationChannelNotificationRule)NotificationServiceTelegramServicez#stream_processor.notification_tasksT   <   )bindmax_retriesdefault_retry_delay)messagechat_idc              
   C   s   zHt d t }|||}t d d|di d|pB|jdW S  tk
r } zlt d|  | jj	| j
k rt d| jj	d	  d
 | j|dn"t d dt|dd W Y S W 5 d}~X Y nX dS )az  
    Send a message via Telegram with retry logic.
    
    This task provides a simple interface for sending Telegram messages
    with automatic retry handling for failed deliveries.
    
    Args:
        message (str): Message text to send
        chat_id (str, optional): Target chat ID, uses default if not provided
        
    Returns:
        dict: Delivery result
    zSending Telegram messagez"Telegram message sent successfullyTresult
message_id)successr   r   z!Failed to send Telegram message: z#Retrying Telegram message (attempt r	   )excz)Max retries exceeded for Telegram messageFr   errorretries_exhaustedN)loggerinfor   send_messagegetdefault_chat_id	Exceptionr   requestretriesr   retrystr)selfr   r   telegram_servicer   e r,   =/var/www/html/StreamProcessor/src/apps/notifications/tasks.pysend_telegram_message   s&    


r.      x   )notification_idc              
   C   s  zt d|  tjj|d}| rHt d| d dddW S t }||}|rt d| d dt|j	|j
j|jr|j ndd	W S d
| }t | | r| jj| jk rt d| jjd  d | jt|ddt|j	||  dW S W n tjk
rB   d| d}t | d|d Y S  tk
r } z^t d|  | jj| jk rt d| jjd  d | j|ddt|dd W Y S d}~X Y nX dS )aG  
    Process and deliver a notification.
    
    This task handles the delivery of individual notifications through
    their configured channels with retry logic for failed deliveries.
    
    Args:
        notification_id (str): UUID of the notification to process
        
    Returns:
        dict: Processing result
    zProcessing notification: )idzNotification z already sentT)r   Zalready_sentz delivered successfullyN)r   r1   channel_typesent_atzFailed to deliver notification z(Retrying notification delivery (attempt r	   r   r   F)r   r1   r   r   zNotification with ID z
 not found)r   r   z Notification processing failed: z*Retrying notification processing (attempt r   )r   r    r
   objectsr"   is_sentr   _deliver_notificationr(   r2   channelr3   r4   	isoformatr   	can_retryr%   r&   r   r'   r$   DoesNotExist)r)   r1   notificationnotification_servicer   	error_msgr+   r,   r,   r-   process_notificationE   sL    



r?   c                  C   s  zt d tjjdt dd} d}| D ]}z0d|_|j	dgd t
t|j |d	7 }W q. tk
r } z4t d
|j d|  |d|  W Y q.W 5 d}~X Y q.X q.t d| d d|dW S  tk
r
 } zt d|   W 5 d}~X Y nX dS )z
    Process all pending notifications that are ready for delivery.
    
    This periodic task finds notifications that are scheduled for
    delivery and queues them for processing.
    
    Returns:
        dict: Processing results
    z Processing pending notificationspending)statusZscheduled_at__ltescheduled_atr   
processingrA   update_fieldsr	   zFailed to queue notification : zQueue failed: NzQueued z notifications for processingT)r   Znotifications_queuedz(Pending notification processing failed: )r   debugr
   r5   filterr   noworder_byrA   saver?   delayr(   r2   r$   r   mark_failedr    )pending_notificationsZqueued_countr<   r+   r,   r,   r-   process_pending_notifications   s4    
rO   c               
   C   st   z:t d t } | jdd}t d| d d|dW S  tk
rn } zt d|   W 5 d	}~X Y nX d	S )
z
    Retry notifications that failed delivery but are eligible for retry.
    
    This periodic task identifies failed notifications that can be
    retried and queues them for another delivery attempt.
    
    Returns:
        dict: Retry results
    zRetrying failed notifications   )max_age_hourszRetried z failed notificationsT)r   Znotifications_retriedz'Failed notification retry task failed: N)r   rG   r   retry_failed_notificationsr    r$   r   )r=   retry_countr+   r,   r,   r-   rR      s    
rR   c                  C   s   zt d ddlm}  d}d}t | |d }t | |d }tjjd|d}|	 }|
  tjjd	|d
}|	 }|
  tjjd|d
}	|		 }
|	
  || |
 }t d| d| d|
 d| d	 d|||
|dW S  tk
r } zt d|   W 5 d}~X Y nX dS )z
    Clean up old notification records to manage database size.
    
    This periodic task removes old notification records that are
    no longer needed for auditing or retry purposes.
    
    Returns:
        dict: Cleanup results
    zCleaning up old notificationsr   	timedelta      )days	completed)rA   Zsent_at__ltfailed)rA   Zcreated_at__lt	cancelledz Notification cleanup completed: z sent, z	 failed, z cancelled (total: r   T)r   Zsent_deletedZfailed_deletedZcancelled_deletedtotal_deletedz"Notification cleanup task failed: N)r   rG   datetimerU   r   rI   r
   r5   rH   countdeleter    r$   r   )rU   Zsent_retention_daysZfailed_retention_daysZsent_cutoffZfailed_cutoffZold_sent
sent_countZ
old_failedZfailed_countZold_cancelledcancelled_countr\   r+   r,   r,   r-   cleanup_old_notifications   sL    
rb   c                  C   s8  zt d tjjdd} d}d}i }| D ]}zFd}d}|jdkr| }|drd|dsnd	}d
}nJzt|d |d d}W n0 t	k
r }	 zd	}d|	 }W 5 d}	~	X Y nX nN|jdkr|
 }|dsd	}d}n(|jdkr| }|dsd	}d}||jkrP||_|jdgd |r2dnd}
t d|j d|
 d ||d||j< |rp|d7 }n|d7 }W q, t	k
r }	 z8t d|j d|	  d	t|	d||j< |d7 }W 5 d}	~	X Y q,X q,t d| d| d  d|||d!W S  t	k
r2 }	 zt d"|	   W 5 d}	~	X Y nX dS )#a  
    Validate notification channel configurations and connectivity.
    
    This periodic task checks that notification channels are properly
    configured and can successfully deliver test messages.
    
    Returns:
        dict: Validation results
    z Validating notification channelsT	is_activer   Ntelegram	bot_tokenr   FzMissing bot_token or chat_id)rf   r   zTelegram validation failed: email
recipientszNo recipients configuredwebhookurlzNo webhook URL configuredrd   rD   	activatedZdeactivatedzChannel  z based on validation)validr   r	   zFailed to validate channel rF   zChannel validation completed: z valid, z invalid)r   Zvalid_channelsZinvalid_channelsresultsz Channel validation task failed: )r   rG   r   r5   rH   r3   get_telegram_configr"   r   r$   get_email_configget_webhook_configrd   rK   r    namer   r(   )channelsZvalid_countZinvalid_countZvalidation_resultsr8   Zchannel_validerror_messageconfigr*   r+   Zstatus_changer,   r,   r-   validate_notification_channels%  sv    






rv   )
event_typecontextc              
   C   s   zpt d|   t }|j| |d}|rPt d|   d| t| dW S t d|   d| dd	W S W n4 tk
r } zt d
|   W 5 d}~X Y nX dS )a  
    Send notifications based on event type and notification rules.
    
    This task provides the main interface for triggering notifications
    from other parts of the system based on events and rules.
    
    Args:
        event_type (str): Type of event that occurred
        context (Dict[str, Any]): Event context data for templates
        
    Returns:
        dict: Notification results
    z#Processing notification for event: )template_typerx   z*Notification sent successfully for event: T)r   rw   Zcontext_keysz!No notifications sent for event: FZ&no_applicable_rules_or_delivery_failed)r   rw   reasonz Rule-based notification failed: N)	r   r    r   send_notificationlistkeyswarningr$   r   )rw   rx   r=   r   r+   r,   r,   r-   send_notification_via_rule  s*    
r   c               
   C   s`  z"t d ddlm}  t }|| dd }tjj|d	 }tjj|dd	 }tjj|d	d	 }tjjd
d	 }d}|dkr|| d }i }t
jjddD ]B}	tjj|	|d}
|
	 |
jdd	 |
jd	d	 d||	j< qt d|dd dd||||t|d|t  d	W S  tk
rZ } zt d|   W 5 d}~X Y nX dS )z
    Generate a periodic report about notification system performance.
    
    This task creates reports about notification delivery rates,
    channel performance, and system health.
    
    Returns:
        dict: Report data
    zGenerating notification reportr   rT   rP   )hours)created_at__gterY   )r   rA   rZ   r@   )rA   d   Trc   )r8   r   )totalsentrZ   zNotification report: z.1fz% delivery rater	   )	r   Zperiod_hourstotal_notificationssent_notificationsfailed_notificationsrN   delivery_ratechannel_performance	timestampz'Notification report generation failed: N)r   rG   r]   rU   r   rI   r
   r5   rH   r^   r   rr   r    roundr9   r$   r   )rU   end_time
start_timer   r   r   rN   r   Zchannel_statsr8   channel_notificationsr+   r,   r,   r-   generate_notification_report  s\    





r   )N)__doc__loggingtypingr   r   r   r   celeryr   django.utilsr   django.confr   modelsr
   r   r   servicesr   r   	getLoggerr   r(   r.   r?   rO   rR   rb   rv   r   r   r,   r,   r,   r-   <module>   s0   
.J
0

C
a.