o
    1dhY                     @   s*  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 d dlmZmZmZmZmZmZ d dlZd dlmZmZ ed	Zeeed
dedefddZeeed
defddZeeed
defddZeeed
dedefddZeeed
defddZeeed
dedefddZ eeed
defddZ!eeed
dedefddZ"eeed
defddZ#eeed
dedefdd Z$eeed
defd!d"Z%eeed
dedefd#d$Z&d%efd&d'Z'd(ed)efd*d+Z(d,efd-d.Z)d/e*d0e+fd1d2Z,d d3lm-Z- dS )4    )	post_savepost_deletepre_save
pre_delete)receiver)cache)timezone)transaction)	TVChannelBroadcastNetworkGeographicZoneChannelCoverageContentScheduleAudienceDemographicsN)AnyOptionalzadtlas.channels.signals)senderinstancecreatedc              
      s$  zn|rt d j d j d jr jjnd  nt d j d j d dd j d	 j d
dg} jrL|d jj d jj g |D ]}t| qN jr^t	 j |rlt
 fdd W dS W dS  ty } zt jd j dt| dd W Y d}~dS d}~ww )a  
    Handle post-save operations for TV channels.
    
    Performs the following actions:
    - Clear relevant cache entries
    - Log channel creation/updates
    - Update network statistics
    - Trigger analytics updates
    
    Args:
        sender: The model class (TVChannel)
        instance: The saved channel instance
        created: Whether this is a new instance
        **kwargs: Additional keyword arguments
    zNew TV channel created:  (z) on network NonezTV channel updated: )channel_statisticschannel_detail_channel_schedule_active_channels_listnetwork_channel_countsnetwork_channels_network_detail_c                         t d jS )NZchannel_created_schedule_analytics_updateid r   r#   IC:\Users\vibe-look\OneDrive\Desktop\Adtlas_V\src\apps\channels\signals.py<lambda>P       z#channel_post_save.<locals>.<lambda>z&Error in channel post_save signal for : Texc_infoN)loggerinfoname	call_signnetworkr"   extendr   delete_update_network_channel_countr	   	on_commit	Exceptionerrorstrr   r   r   kwargscache_keys_to_clear	cache_keyer#   r$   r%   channel_post_save   sJ   

	


r<   c              
   K   s   z?t d|j d|j d t|dr|jr|jjnd|_|jj	t
 d }|dkr=t d|j d	| d
 W dS W dS  tyb } zt jd|j dt| dd W Y d}~dS d}~ww )a  
    Handle pre-delete operations for TV channels.
    
    Performs cleanup operations before channel deletion:
    - Log the deletion
    - Store related data for post-deletion cleanup
    - Validate deletion constraints
    
    Args:
        sender: The model class (TVChannel)
        instance: The channel instance being deleted
        **kwargs: Additional keyword arguments
    zTV channel being deleted: r   r   _network_id_for_cleanupN)Zend_time__gter   zDeleting channel z with z active schedule entriesz'Error in channel pre_delete signal for r(   Tr)   )r+   warningr-   r.   hasattrr/   r"   r=   schedule_entriesfilterr   nowcountr4   r5   r6   )r   r   r8   Zactive_schedulesr;   r#   r#   r%   channel_pre_deleteZ   s.   

rD   c              
      s   zSt d j d j d dd j d j ddg}|D ]}t| q t d	d
}|rHztj	j
|d}t| W n
 tjyG   Y nw t fdd W d
S  tyr } zt jdt| dd W Y d
}~d
S d
}~ww )aV  
    Handle post-delete operations for TV channels.
    
    Performs cleanup after channel deletion:
    - Clear cache entries
    - Update network statistics
    - Log the completion
    
    Args:
        sender: The model class (TVChannel)
        instance: The deleted channel instance
        **kwargs: Additional keyword arguments
    zTV channel deleted: r   r   r   r   r   r   r   r=   Nr"   c                      r   )NZchannel_deletedr    r#   r$   r#   r%   r&      r'   z%channel_post_delete.<locals>.<lambda>z%Error in channel post_delete signal: Tr)   )r+   r,   r-   r.   r"   r   r1   getattrr   objectsgetr2   DoesNotExistr	   r3   r4   r5   r6   )r   r   r8   r9   r:   
network_idr/   r;   r#   r$   r%   channel_post_delete   s<   



rK   c              
   K   s   z5|rt d|j  n	t d|j  ddd|j d|j dg}|D ]}t| q't| W dS  tyX } zt jd|j d	t	| d
d W Y d}~dS d}~ww )a  
    Handle post-save operations for broadcast networks.
    
    Args:
        sender: The model class (BroadcastNetwork)
        instance: The saved network instance
        created: Whether this is a new instance
        **kwargs: Additional keyword arguments
    zNew broadcast network created: zBroadcast network updated: network_listnetwork_statisticsr   r   active_networks_listz&Error in network post_save signal for r(   Tr)   N)
r+   r,   r-   r"   r   r1   r2   r4   r5   r6   r7   r#   r#   r%   network_post_save   s(   

rO   c              
   K   s   z&t d|j  ddd|j d|j ddg}|D ]}t| qW dS  tyE } zt jdt| d	d
 W Y d}~dS d}~ww )z
    Handle post-delete operations for broadcast networks.
    
    Args:
        sender: The model class (BroadcastNetwork)
        instance: The deleted network instance
        **kwargs: Additional keyword arguments
    zBroadcast network deleted: rL   rM   r   r   rN   r   z%Error in network post_delete signal: Tr)   N)	r+   r>   r-   r"   r   r1   r4   r5   r6   r   r   r8   r9   r:   r;   r#   r#   r%   network_post_delete   s&   


	rQ   c              
   K   s   z<|rt d|j d|j d nt d|j d|j d ddd|j d|j d	d
g}|D ]}t| q2W dS  ty_ } zt jd|j dt	| dd W Y d}~dS d}~ww )a  
    Handle post-save operations for geographic zones.
    
    Args:
        sender: The model class (GeographicZone)
        instance: The saved zone instance
        created: Whether this is a new instance
        **kwargs: Additional keyword arguments
    zNew geographic zone created: r   r   zGeographic zone updated: 	zone_listzone_statisticszone_detail_zone_channels_coverage_map_dataactive_zones_listz#Error in zone post_save signal for r(   Tr)   N)
r+   r,   r-   	zone_typer"   r   r1   r4   r5   r6   r7   r#   r#   r%   zone_post_save  s2   

	rY   c              
   K   s   z,t d|j d|j d ddd|j d|j dd	d
g}|D ]}t| q"W dS  tyK } zt jdt	| dd W Y d}~dS d}~ww )z
    Handle post-delete operations for geographic zones.
    
    Args:
        sender: The model class (GeographicZone)
        instance: The deleted zone instance
        **kwargs: Additional keyword arguments
    zGeographic zone deleted: r   r   rR   rS   rT   rU   rV   rW   r   z"Error in zone post_delete signal: Tr)   N)
r+   r>   r-   rX   r"   r   r1   r4   r5   r6   rP   r#   r#   r%   zone_post_delete1  s,   



rZ   c              
   K   s   z\|rt d|jj d|jj d|j d nt d|jj d|jj d|j d ddd|jj d	|jj d
|jj d|jj dg}|D ]}t| qKt	|j|j W dS  t
y{ } zt jdt| dd W Y d}~dS d}~ww )a	  
    Handle post-save operations for channel coverage.
    
    Args:
        sender: The model class (ChannelCoverage)
        instance: The saved coverage instance
        created: Whether this is a new instance
        **kwargs: Additional keyword arguments
    z#New coverage relationship created:  in r   z%)zCoverage relationship updated: rV   coverage_statisticschannel_coverage_zone_coverage_r   rT   r   z$Error in coverage post_save signal: Tr)   N)r+   r,   channelr-   zonecoverage_percentager"   r   r1   _update_coverage_statisticsr4   r5   r6   r7   r#   r#   r%   coverage_post_saveY  sD   
rc   c              
   K   s   z9t d|jj d|jj  ddd|jj d|jj d|jj d|jj d	g}|D ]}t| q/W dS  tyX } zt j	d
t
| dd W Y d}~dS d}~ww )z
    Handle post-delete operations for channel coverage.
    
    Args:
        sender: The model class (ChannelCoverage)
        instance: The deleted coverage instance
        **kwargs: Additional keyword arguments
    zCoverage relationship deleted: r[   rV   r\   r]   r^   r   rT   r   z&Error in coverage post_delete signal: Tr)   N)r+   r,   r_   r-   r`   r"   r   r1   r4   r5   r6   rP   r#   r#   r%   coverage_post_delete  s0   

rd   c              
   K   s   z:|rt d|j d|jj d|j  d|jj d|jj ddg}|D ]}t| q'|r8t	| W dS W dS  t
yY } zt jdt| d	d
 W Y d}~dS d}~ww )a
  
    Handle post-save operations for content schedules.
    
    Args:
        sender: The model class (ContentSchedule)
        instance: The saved schedule instance
        created: Whether this is a new instance
        **kwargs: Additional keyword arguments
    zNew schedule entry created:  on z at r   r   Zupcoming_programsZschedule_statisticsz$Error in schedule post_save signal: Tr)   N)r+   r,   program_titler_   r-   
start_timer"   r   r1   _check_schedule_conflictsr4   r5   r6   r7   r#   r#   r%   schedule_post_save  s4   
ri   c              
   K   s   zH|j r@|jrC|j |jkrtd|j d|j  d|j d |j |j }| dkrFtd|j d| d d	d
 W dS W dS W dS W dS  tyg } ztjdt| dd W Y d}~dS d}~ww )aw  
    Handle pre-save operations for content schedules.
    
    Validates schedule data before saving:
    - Ensure end time is after start time
    - Check for reasonable duration
    - Validate time zones
    
    Args:
        sender: The model class (ContentSchedule)
        instance: The schedule instance being saved
        **kwargs: Additional keyword arguments
    zInvalid schedule timing for z: end time (z) is not after start time (r   iQ z#Long program duration detected for r(     z.1fz hoursz#Error in schedule pre_save signal: Tr)   N)	end_timerg   r+   r5   rf   total_secondsr>   r4   r6   )r   r   r8   durationr;   r#   r#   r%   schedule_pre_save  s4   



rn   c              
      s   zE|rt d jj d j  d jj d jj ddg}|D ]}t| q#t	 
  j jdkrCt fdd	 W dS W dS  tyd } zt jd
t| dd W Y d}~dS d}~ww )a  
    Handle post-save operations for audience demographics.
    
    Args:
        sender: The model class (AudienceDemographics)
        instance: The saved demographics instance
        created: Whether this is a new instance
        **kwargs: Additional keyword arguments
    z"New demographics data created for re   Zchannel_demographics_r   Zdemographics_statisticsZaudience_trends   c                      s   t d jjS )NZdemographics_updated)r!   r_   r"   r#   r$   r#   r%   r&   %  s    z(demographics_post_save.<locals>.<lambda>z(Error in demographics post_save signal: Tr)   N)r+   r,   r_   r-   measurement_dater"   r   r1   r   rB   datedaysr	   r3   r4   r5   r6   r7   r#   r$   r%   demographics_post_save  s4   

rs   r/   c              
   C   s   z0| j jdd }| j  }tjd| j ||ddd td| j d| d	| d
 W dS  t	yQ } zt
d| j dt|  W Y d}~dS d}~ww )z{
    Update the channel count for a broadcast network.
    
    Args:
        network: The broadcast network to update
    T)	is_activeZnetwork_channel_count_)activetotalrj   timeoutz"Updated channel count for network r(   z	 active, z totalz)Error updating network channel count for N)channelsrA   rC   r   setr"   r+   debugr-   r4   r5   r6   )r/   active_counttotal_countr;   r#   r#   r%   r2   3  s*   



r2   r_   r`   c              
   C   s   zOt jj| d}| r#|jtddd }tjd| j	 |dd t jj|d}| rM|
 |jtddd d	}tjd
|j	 |dd W dS W dS  tyl } ztdt|  W Y d}~dS d}~ww )z
    Update coverage statistics for a channel and zone.
    
    Args:
        channel: The TV channel
        zone: The geographic zone
    )r_   ra   )avgr~   Zchannel_avg_coverage_rj   rw   )r`   )channel_countavg_coverageZzone_coverage_stats_z$Error updating coverage statistics: N)r   rG   rA   exists	aggregatemodelsAvgr   rz   r"   rC   r4   r+   r5   r6   )r_   r`   channel_coverager   Zzone_coverageZ
zone_statsr;   r#   r#   r%   rb   P  sD   

rb   schedulec              
   C   s   zR| j sW dS tjj| j| j | jdj| jd}| rM|	 }t
d| j d| jj d| d |dd D ]}t
d	|j d
|j d|j  d q8W dS W dS  tyo } zt
dt|  W Y d}~dS d}~ww )z}
    Check for schedule conflicts with existing programs.
    
    Args:
        schedule: The content schedule to check
    N)r_   Zstart_time__ltZend_time__gtrE   zSchedule conflict detected for re   r(   z overlapping programs   z  Conflicts with: r   z - r   z#Error checking schedule conflicts: )rk   r   rG   rA   r_   rg   excluder"   r   rC   r+   r>   rf   r-   r4   r5   r6   )r   	conflictsZconflict_countZconflictr;   r#   r#   r%   rh   |  sF   

rh   
event_type	object_idc              
   C   sl   zt d|  d|  td td W dS  ty5 } zt dt|  W Y d}~dS d}~ww )z
    Schedule an analytics update for background processing.
    
    Args:
        event_type: Type of event that triggered the update
        object_id: ID of the object that changed
    zAnalytics update scheduled: z for object Zanalytics_summaryZchannel_performance_metricsz#Error scheduling analytics update: N)r+   r,   r   r1   r4   r5   r6   )r   r   r;   r#   r#   r%   r!     s   
r!   )r   ).Zdjango.db.models.signalsr   r   r   r   django.dispatchr   django.core.cacher   django.utilsr   	django.dbr	   Zchannels.modelsr
   r   r   r   r   r   loggingtypingr   r   	getLoggerr+   boolr<   rD   rK   rO   rQ   rY   rZ   rc   rd   ri   rn   rs   r2   rb   rh   r6   intr!   r   r#   r#   r#   r%   <module>   sL    


A
(
8
&
$
(
'
.
(
'
+-,&