o
    0ehe                     @   s   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mZ d dlmZ G dd	 d	eZG d
d deZG dd deZG dd deZG dd deZG dd deZdS )    N)Decimal)models)reverse)gettext_lazy)MinValueValidatorMaxValueValidator)	BaseModelc                	   @   s  e Zd ZdZdedfdedfdedfded	fd
edfdedfgZejdej	deddZ
ejdededdZejddededdZejdeededdZejdejdddeded d!Zejdded"ed#d$Zejdded%ed&d$Zejd'd(dded)ed*d+Zejd'd(dded,ed-d+Zejd.d/ed0ed1d2Zejded3ed4d5ZG d6d7 d7Zd8d9 Zd:d; Zed<d= Zd>d? Z d@S )AGeographicZonea  
    Geographic zones for targeted TV advertising.
    
    Represents geographic regions where TV channels broadcast and where
    advertising campaigns can be targeted. Supports hierarchical zones
    (country > state > city > DMA) for precise geographic targeting.
    countryCountrystatezState/ProvincecityCityZdmazDesignated Market AreaZpostalzPostal CodeZcustomzCustom ZoneTFzZone IDprimary_keydefaulteditableverbose_name   z	Zone Namez@Name of the geographic zone (e.g., "New York DMA", "California")
max_lengthr   	help_text   z	Zone Codez7Unique identifier code for the zone (e.g., "NYC", "CA")r   uniquer   r   z	Zone TypezType of geographic zoner   choicesr   r   selfchild_zoneszParent Zonez4Parent geographic zone for hierarchical organization	on_deletenullblankrelated_namer   r   Z
Populationz(Total population in this geographic zoner!   r"   r   r   zTV Householdsz+Number of households with television access
      LatitudezGeographic latitude coordinate
max_digitsdecimal_placesr!   r"   r   r   	LongitudezGeographic longitude coordinate2   UTCZTimezonez9Primary timezone for this zone (e.g., "America/New_York")r   r   r   r   Activez5Whether this zone is active for advertising targetingr   r   r   c                   @   sP   e Zd ZedZedZddgZejddgdejddgdejdgdgZ	d	S )
zGeographicZone.MetazGeographic ZonezGeographic Zones	zone_typename	is_activefieldsparent_zonecodeN
__name__
__module____qualname___r   verbose_name_pluralorderingr   Indexindexes rA   rA   HC:\Users\vibe-look\OneDrive\Desktop\Adtlas_V\src\apps\channels\models.pyMetah   s    rC   c                 C   s   | j  d|   dS N ())r2   Zget_zone_type_displayr   rA   rA   rB   __str__r      zGeographicZone.__str__c                 C      t dd| jidS )Nzchannels:zone_detailpkkwargsr   rK   rG   rA   rA   rB   get_absolute_urlu      zGeographicZone.get_absolute_urlc                 C   s4   | j g}| j}|r|d|j  |j}|s	d|S )z,Get the full hierarchical path of this zone.r   z > N)r2   r6   insertjoin)r   Z	hierarchycurrentrA   rA   rB   full_hierarchyx   s   
zGeographicZone.full_hierarchyc                 C      | j jdd S )z$Get the count of direct child zones.Tr3   N)r   filtercountrG   rA   rA   rB   get_child_zones_count   s   z$GeographicZone.get_child_zones_countN)!r9   r:   r;   __doc__r<   Z
ZONE_TYPESr   	UUIDFielduuiduuid4id	CharFieldr2   r7   r1   
ForeignKeyCASCADEr6   PositiveIntegerField
populationtv_householdsDecimalFieldlatitude	longitudetimezoneBooleanFieldr3   rC   rH   rO   propertyrT   rY   rA   rA   rA   rB   r	      s    
	




		

	r	   c                	   @   s  e Zd ZdZdedfdedfdedfded	fd
edfdedfgZejdededdZejdededdZ	ejdeededdZ
ejdejdddededdZejddeded d!Zejdded"ed#d$Zejded%ed&d'Zejded(ed)d'Zejded*ed+d'Zejeded,ed-d.Zejded/ed0d1ZG d2d3 d3Zd4d5 Zd6d7 Zed8d9 Zd:d; Z d<S )=BroadcastNetworkz
    Television broadcasting networks and media companies.
    
    Represents major TV networks (ABC, NBC, CBS, etc.) and their hierarchical
    relationships, including parent companies, subsidiaries, and affiliates.
    	broadcastBroadcast NetworkcablezCable Network	satellitezSatellite Network	streamingzStreaming ServicelocalzLocal StationZsyndicationzSyndication Networkr   zNetwork Namez%Full name of the broadcasting networkr   r,   z
Short Namez5Abbreviated name or call letters (e.g., "ABC", "NBC")r   zNetwork TypezType of broadcasting networkr   r   Tsubsidiary_networkszParent NetworkzParent company or network groupr   zFounded Datez%Date when the network was establishedr$   ZHeadquartersz Location of network headquartersr   r"   r   r   Website URLzOfficial website of the networkr"   r   r   Logo URLzURL to the network logo imageDescriptionz7Detailed description of the network and its programmingTarget Demographics1JSON data describing target audience demographicsr   r"   r   r   r/   z(Whether this network is currently activer0   c                   @   sN   e Zd ZedZedZddgZejddgdejdgdejdgdgZ	d	S )
zBroadcastNetwork.Metarm   zBroadcast Networksnetwork_typer2   r3   r4   parent_network
short_nameNr8   rA   rA   rA   rB   rC      s    rC   c                 C      | j  d| j dS rD   )r2   r}   rG   rA   rA   rB   rH         zBroadcastNetwork.__str__c                 C   rJ   )Nzchannels:network_detailrK   rL   rN   rG   rA   rA   rB   rO      rP   z!BroadcastNetwork.get_absolute_urlc                 C   rU   )z8Get the number of channels associated with this network.TrV   N)channelsrW   rX   rG   rA   rA   rB   channel_count   s   zBroadcastNetwork.channel_countc                 C   s8   t | jjdd}| jjddD ]	}||  q|S )z(Get all subsidiary networks recursively.TrV   N)listrr   rW   extendget_subsidiary_networks)r   ZsubsidiariesZ
subsidiaryrA   rA   rB   r      s   z(BroadcastNetwork.get_subsidiary_networksN)!r9   r:   r;   rZ   r<   ZNETWORK_TYPESr   r_   r2   r}   r{   r`   ra   r|   	DateFieldZfounded_dateZheadquarters_locationURLFieldwebsite_urllogo_url	TextFielddescription	JSONFielddicttarget_demographicsri   r3   rC   rH   rO   rj   r   r   rA   rA   rA   rB   rk      s    





		

rk   c                   @   s  e Zd ZdZdedfdedfdedfded	fd
edfdedfgZdedfdedfdedfdedfdedfdedfdedfdedfdedfd ed!fd"ed#fd$ed%fgZejd&ed'ed(d)Z	ejd*d+ed,ed-d.Z
ejd*ed/ed0d)Zejd*eed1ed2d3Zejeejd4ed5ed6d7Zejed8d4ed9ed:d;Zejd<d=ed>ed?d@Zejed+edAedBdCZejd*eedDedEd3Zejed+edFedGdCZejd+edHedIdJZejd+edKedLdMZejd+edNedOdMZej d+edPedQdMZ!ej"d+d+edRedSdTZ#ejd+edUedVdJZ$ejdWedXedYdJZ%ejd+edZed[dJZ&G d\d] d]Z'd^d_ Z(d`da Z)e*dbdc Z+ddde Z,dfS )g	TVChannelz
    Television channels with comprehensive metadata and relationships.
    
    Represents individual TV channels with their broadcasting details,
    network affiliations, geographic coverage, and advertising inventory.
    ZterrestrialzTerrestrial/Over-the-Airrn   zCable Channelro   zSatellite ChannelZiptvzIPTV Channelrp   zStreaming ChannelradiozRadio StationZgeneralzGeneral EntertainmentnewszNews & InformationsportsZSportsZmoviesZMoviesZkidszChildren's ProgrammingZ	lifestylezLifestyle & RealityZdocumentaryZDocumentaryZmusicZMusicZ	religiousZ	ReligiousZeducationalZEducationalZshoppingZShoppingZadultzAdult Contentr   zChannel NamezFull name of the TV channelr   r   Tz	Call Signz:Official call sign or identifier (e.g., "WABC-TV", "ESPN")r   zChannel Numberz?Channel number on cable/satellite systems (e.g., "7.1", "ESPN")zChannel TypezType of broadcasting technologyr   r   ZNetworkz7Broadcasting network that owns or operates this channel)r    r#   r   r   ChannelCoveragezCoverage Zonesz0Geographic zones where this channel is available)throughr#   r   r   r%   enzPrimary Languagez4Primary language of channel content (ISO 639-1 code)r.   zSecondary Languagesz-Additional languages supported by the channelrz   zContent Categoryz'Primary content category of the channelrx   ry   zHD Availablez1Whether the channel broadcasts in high definitionr0   rt   zOfficial website of the channelru   rv   zURL to the channel logo imagerw   z7Detailed description of the channel and its programmingzLaunch Datez"Date when the channel was launchedr$   r/   z9Whether this channel is currently active and broadcastingFzPremium Channelz%Whether this is a premium/pay channelzAdvertising Enabledz.Whether advertising is allowed on this channelc                   @   sh   e Zd ZedZedZddgZejddgdejddgdejd	gdejd
gdejdgdgZ	dS )zTVChannel.Metaz
TV ChannelzTV Channelschannel_numberr2   channel_typer3   r4   networkcontent_category	call_signNr8   rA   rA   rA   rB   rC   |      rC   c                 C   r~   rD   )r2   r   rG   rA   rA   rB   rH     r   zTVChannel.__str__c                 C   rJ   )Nzchannels:channel_detailrK   rL   rN   rG   rA   rA   rB   rO     rP   zTVChannel.get_absolute_urlc                 C   s   t dd | jjdddD S )z3Calculate total population covered by this channel.c                 s   s    | ]	}|j jp	d V  qdS )r   N)zonerc   ).0ZcoveragerA   rA   rB   	<genexpr>  s
    

z6TVChannel.total_coverage_population.<locals>.<genexpr>T)Zzone__is_activer3   N)sumcoverage_detailsrW   rG   rA   rA   rB   total_coverage_population  s   z#TVChannel.total_coverage_populationc                 C   s   | j j|ddS )z$Get coverage zones filtered by type.T)r1   r3   N)coverage_zonesrW   )r   r1   rA   rA   rB   get_coverage_zones_by_type  s   z$TVChannel.get_coverage_zones_by_typeN)-r9   r:   r;   rZ   r<   ZCHANNEL_TYPESZCONTENT_CATEGORIESr   r_   r2   r   r   r   r`   rk   ra   r   ManyToManyFieldr	   r   Zprimary_languager   r   Zsecondary_languagesr   r   r   ri   Zhd_availabler   r   r   r   r   r   Zlaunch_dater3   Z
is_premiumZadvertising_enabledrC   rH   rO   rj   r   r   rA   rA   rA   rB   r      s   




















r   c                	   @   s  e Zd ZdZdedfdedfdedfded	fd
edfgZejdej	deddZ
ejeejdeddZejeejdeddZejdedededdZejddededgedededd Zejdded!ed"d#Zejddddededged$ed%d&Zejdded'ed(d#Zejded)ed*d+Zejded,ed-d.Z G d/d0 d0Z!d1d2 Z"e#d3d4 Z$d5S )6r   z
    Through model for Channel-Zone relationships with coverage details.
    
    Defines the specific coverage relationship between a TV channel and
    a geographic zone, including signal strength, availability, and
    subscriber information.
    Z	excellentzExcellent (90-100%)ZgoodzGood (70-89%)ZfairzFair (50-69%)ZpoorzPoor (30-49%)ZmarginalzMarginal (10-29%)TFzCoverage IDr   r   Channelr    r#   r   Zchannel_coverageZoner   zSignal Strengthz(Quality of signal reception in this zone)r   r   r   r   r         r   d   z100.00zCoverage Percentagez.Percentage of zone area covered by the channel)r)   r*   
validatorsr   r   r   zSubscriber Countz"Number of subscribers in this zoner$   zPenetration Ratez7Percentage of households that subscribe to this channel)r)   r*   r!   r"   r   r   r   zLaunch Date in Zonez3Date when the channel became available in this zoner/   z)Whether this coverage is currently activer0   Notesz,Additional notes about coverage in this zoneru   c                   @   sV   e Zd ZedZedZddgZddgZej	ddgdej	dgdej	dgdgZ
d	S )
zChannelCoverage.MetazChannel Coveragechannelr   channel__nameZ
zone__namer4   signal_strengthr3   Nr9   r:   r;   r<   r   r=   unique_togetherr>   r   r?   r@   rA   rA   rA   rB   rC         rC   c                 C   s   | j j d| jj S )Nz in )r   r2   r   rG   rA   rA   rB   rH     rI   zChannelCoverage.__str__c                 C   s(   | j jr| jrt| j j| jd  S dS )zDEstimate potential viewers based on zone population and penetration.r   N)r   rd   penetration_rateintrG   rA   rA   rB   estimated_viewers  s   z!ChannelCoverage.estimated_viewersN)%r9   r:   r;   rZ   r<   ZSIGNAL_STRENGTH_CHOICESr   r[   r\   r]   r^   r`   r   ra   r   r	   r   r_   r   re   r   r   r   Zcoverage_percentagerb   Zsubscriber_countr   r   Zlaunch_date_in_zoneri   r3   r   notesrC   rH   rj   r   rA   rA   rA   rB   r     s    
	



	r   c                   @   s$  e Zd ZdZdedfdedfdedfded	fd
edfdedfdedfdedfdedfg	Zejdej	deddZ
ejeejdeddZejdededdZejdeded d!Zejd"eed#ed$d%Zejed&ed'd(Zejed)ed*d(Zejed+ed,d(Zejd-ded.ed/d0Zejd1ded2ed3d0Zejeded4ed5d6Zejd7ed8ed9d:Zejd7ed;ed<d:Zej ded=ed>d:Z!ej ded?ed@d:Z"ejd-dedAedBd0Z#G dCdD dDZ$dEdF Z%dGdH Z&e'dIdJ Z(dKdL Z)dMS )NContentSchedulez
    Electronic Program Guide (EPG) integration for content scheduling.
    
    Manages the programming schedule for TV channels, including show times,
    content metadata, and advertising break opportunities.
    ZlivezLive ProgrammingZrecordedzPre-recordedZrerunzRerun/RepeatZmovieZMovieZseriesz	TV Seriesr   zNews Programr   zSports EventZ
commercialzCommercial BreakZinfomercialZInfomercialTFzSchedule IDr   Zschedule_entriesr   r   i,  zProgram Titlez)Title of the scheduled program or contentr   rw   z+Detailed description of the program contentru   r   zContent TypezType of scheduled contentr   z
Start Timez#Scheduled start time of the programr   r   zEnd Timez!Scheduled end time of the programzDuration (Minutes)zProgram duration in minutesr   ZGenrezProgram genre or categoryrs   r%   zContent Ratingz&Content rating (G, PG, PG-13, R, etc.)rx   z5JSON data describing target audience for this programrz   r   zAdvertising Breaksz0Number of advertising breaks during this programr0   zAd Break Durationz/Total duration of advertising breaks in secondszLive Programz Whether this is a live broadcastZPremierez3Whether this is a premiere episode or first showingzExternal IDz.External system identifier for EPG integrationc                   @   sh   e Zd ZedZedZddgZejddgdejddgdejdgdejdgdejd	gdgZ	d
S )zContentSchedule.MetazContent SchedulezContent Schedulesr   
start_timer4   end_timecontent_typeis_liveexternal_idNr8   rA   rA   rA   rB   rC   r  r   rC   c                 C   s   | j  d| jj d| j S )Nz on z at )titler   r2   r   rG   rA   rA   rB   rH   ~  s   zContentSchedule.__str__c                 C   rJ   )Nzchannels:schedule_detailrK   rL   rN   rG   rA   rA   rB   rO     rP   z ContentSchedule.get_absolute_urlc                 C   s0   ddl m} | }| j|  ko| jkS   S )z)Check if the program is currently airing.r   )rh   N)django.utilsrh   nowr   r   )r   rh   r   rA   rA   rB   is_currently_airing  s   z#ContentSchedule.is_currently_airingc                 C   sp   ddl m} | jr2| jr4| j| jkr|td| j| j  d }t|| j dkr6t|| _dS dS dS dS )zValidate schedule entry data.r   )ValidationErrorz#Start time must be before end time.<      N)	django.core.exceptionsr   r   r   r<   total_secondsabsduration_minutesr   )r   r   Zcalculated_durationrA   rA   rB   clean  s   zContentSchedule.cleanN)*r9   r:   r;   rZ   r<   ZCONTENT_TYPESr   r[   r\   r]   r^   r`   r   ra   r   r_   r   r   r   r   DateTimeFieldr   r   rb   r   ZgenreZratingr   r   r   Zadvertising_breaksZad_break_durationri   r   Zis_premierer   rC   rH   rO   rj   r   r   rA   rA   rA   rB   r   	  s    









r   c                
   @   s  e Zd ZdZdedfdedfdedfded	fd
edfdedfdedfdedfgZdedfdedfdedfdedfdedfdedfgZeje	ej
dedd Zejeej
ded!d Zejed"ed#d$Zejed%ed&d$Zejeed'ed(d)Zejeed*ed+d)Zejeed,ed-d)Zejeed.ed/d)Zejd0d1d2d2ed3ed4d5Zejed2ed6ed7d8ZG d9d: d:Zd;d< Zed=d> Zed?d@ Z dAS )BAudienceDemographicsz
    Audience demographics and viewership analytics for channels and zones.
    
    Stores demographic data and viewership statistics for targeted
    advertising and audience analysis.
    z2-11zChildren (2-11)z12-17zTeens (12-17)z18-24zYoung Adults (18-24)z25-34zAdults (25-34)z35-44zAdults (35-44)z45-54zAdults (45-54)z55-64zAdults (55-64)z65+zSeniors (65+)z	under-25kzUnder $25,000z25k-50kz$25,000 - $50,000z50k-75kz$50,000 - $75,000z75k-100kz$75,000 - $100,000z	100k-150kz$100,000 - $150,000z	over-150kzOver $150,000Zdemographicsr   r   r   zMeasurement Datez*Date when these demographics were measuredr   zTotal Viewersz+Total number of viewers in this demographiczAge Distributionz$JSON data with age group percentagesr0   zGender Distributionz7JSON data with gender percentages (male, female, other)zIncome Distributionz)JSON data with income bracket percentageszEducation Distributionz*JSON data with education level percentagesr   r   TzViewing Hours/Weekz3Average viewing hours per week for this demographicr(   zPeak Viewing Timesz'JSON array of peak viewing time periodsrz   c                   @   sV   e Zd ZedZedZg dZddgZej	ddgdej	dgdej	d	gdgZ
d
S )zAudienceDemographics.MetazAudience Demographics)r   r   measurement_datez-measurement_dater   r   r   r4   r   total_viewersNr   rA   rA   rA   rB   rC     r   rC   c                 C   s    | j j d| jj d| j dS )Nz demographics in rE   rF   )r   r2   r   r   rG   rA   rA   rB   rH     s    zAudienceDemographics.__str__c                 C   s$   | j sdS t| j  dd dd S )z.Get the age group with the highest percentage.Nc                 S   s   | d S )Nr   rA   )xrA   rA   rB   <lambda>   s    z8AudienceDemographics.primary_age_group.<locals>.<lambda>)keyr   )age_distributionmaxitemsrG   rA   rA   rB   primary_age_group  s   z&AudienceDemographics.primary_age_groupc                 C   s   | j rtt| j d dS dS )z;Calculate a viewer engagement score based on viewing hours.g      @r   r   N)viewing_hours_per_weekminfloatrG   rA   rA   rB   viewer_engagement_score  s   z,AudienceDemographics.viewer_engagement_scoreN)!r9   r:   r;   rZ   r<   Z
AGE_GROUPSZINCOME_BRACKETSr   r`   r   ra   r   r	   r   r   r   rb   r   r   r   r   Zgender_distributionZincome_distributionZeducation_distributionre   r   r   Zpeak_viewing_timesrC   rH   rj   r   r   rA   rA   rA   rB   r     s    















r   )r\   decimalr   	django.dbr   django.urlsr   django.utils.translationr   r<   django.core.validatorsr   r   Zapps.common.modelsr   r	   rk   r   r   r   r   rA   rA   rA   rB   <module>   s   yn -h 