
    h                     R   d dl mZ d dlmZmZ d dlmZmZmZ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 d dlmZmZmZmZmZ d dlmZmZ d d	lmZmZ d d
l m!Z! d dl"m#Z# d dl$m%Z%  ejL                  e'      Z( G d d      Z)	 	 	 ddede*dee*   de*de+de%jX                  fdZ-y)    )Session)funcand_)datetimedate	timedeltatimezone)DictAnyOptionalListN)Counterdefaultdict)PersonaPersonaProfilePersonaAudiencePersonaContextPersonaPerformance)ConnectedAccountMasterAccount)AccountMetricsDailyPostMetricsDaily)CalendarPostType)$get_social_media_dashboard_analytics)schemac                   b	   e Zd ZdZdefdZ	 	 	 dKdedee   deded	e	j                  f
d
ZdLdedee   d	ee   fdZdLdedee   d	ee   fdZdee   ded	e	j"                  fdZde	j"                  d	e	j&                  fdZde	j"                  d	eeef   fdZde	j"                  d	eeef   fdZde	j"                  d	eeef   fdZde	j"                  d	eeef   fdZde	j"                  d	eeef   fdZde	j"                  d	eeef   fdZde	j"                  d	eeef   fdZde	j"                  d	eeef   fdZde	j"                  d	eeef   fdZ de	j"                  d	eeeef      fdZ!de	j"                  d	eeef   fdZ"de	j"                  d	eeef   fdZ#de	j"                  d	eeef   fdZ$de	j"                  d	eeeef      fdZ%de	j"                  d	eeef   fdZ&de	j"                  d	eeef   fd Z'de	j"                  d	eeeef      fd!Z(de	j"                  d	eeef   fd"Z)de	j"                  d	eeef   fd#Z*de	j"                  d	eeef   fd$Z+de	j"                  d	eeef   fd%Z,de	j"                  d	eeef   fd&Z-de	j"                  d	eeef   fd'Z.de	j"                  d	eeef   fd(Z/de	j"                  d	eeef   fd)Z0de	j"                  d	eeef   fd*Z1d+ee   d	eeeef      fd,Z2d+ee   d	e3fd-Z4dedee   d.ee   d/e	j&                  d	ef
d0Z5d1ed/e	j&                  fd2Z6d1ed/e	j&                  fd3Z7d1ed/e	j&                  fd4Z8d1ed/e	j&                  fd5Z9d/e	j&                  d	efd6Z:d/e	j&                  d	eeef   fd7Z;d/e	j&                  d	eeef   fd8Z<d/e	j&                  d	eeeef      fd9Z=d/e	j&                  d	eeef   fd:Z>d/e	j&                  d	eeef   fd;Z?d/e	j&                  d	eeeef      fd<Z@d/e	j&                  d	eeeef      fd=ZAd/e	j&                  d	efd>ZBd/e	j&                  d	efd?ZCd/e	j&                  d	efd@ZDdAed	e	j                  fdBZFdCeGd	e	j                  fdDZIdEeJd	e	j                  fdFZLdGeMd	e	j                  fdHZOdIePd	e	j                  fdJZRy)MPersonaGenerationServicezMService for generating and managing personas based on social media analytics.dbc                     || _         y N)r   )selfr   s     A/var/www/html/hubwallet-dev/src/marketing/apps/persona/service.py__init__z!PersonaGenerationService.__init__   s	        Nstore_id	branch_iddays_to_analyzeforce_refreshreturnc           
      ~   	 | j                  ||      }|r|s|j                  }j                  ||j                  t        j
                        }t        j                  t        j
                        |z
  j                  }|dk  r't        j                  dd| j                  |            S | j                  ||      }|st        j                  dd	      S 	 | j                  ||      }		 | j%                  |	      }| j'                  ||||      }| j(                  j+                          t        j                  dd| j                  |      t-        |      |t        j                  t        j
                        j/                         d      S # t        $ rQ}
t        j!                  d
| dt#        |
              t        j                  ddt#        |
       	      cY d}
~
S d}
~
ww xY w# t        $ rQ}
t        j!                  d| dt#        |
              t        j                  ddt#        |
       	      cY d}
~
S d}
~
ww xY w# t        $ rk}
| j(                  j1                          t        j!                  d| dt#        |
              t        j                  ddt#        |
       	      cY d}
~
S d}
~
ww xY w)a  
        Generate or refresh persona for a store based on social media analytics.
        
        Args:
            store_id: ID of the store
            branch_id: Optional branch ID
            days_to_analyze: Number of days to analyze
            force_refresh: Whether to force refresh existing persona
            
        Returns:
            PersonaGenerationResponse with generated persona data
        N)tzinfo   Tz$Persona already exists and is recent)successmessagedataFz7No connected social media accounts found for this store)r-   r.   z*Error generating analytics data for store z: z#Failed to generate analytics data: z,Error generating persona insights for store z%Failed to generate persona insights: zPersona generated successfully)accounts_analyzeddays_analyzedgenerated_at)r-   r.   r/   generation_metadataz#Error generating persona for store zError generating persona: )_get_existing_persona
updated_atr+   replacer	   utcr   nowdaysr   PersonaGenerationResponse_build_persona_response_get_connected_accounts_generate_analytics_data	Exceptionloggererrorstr_generate_persona_insights_create_or_update_personar   commitlen	isoformatrollback)r!   r%   r&   r'   r(   existing_personar5   days_since_updateconnected_accountsanalytics_dataepersona_insightspersonas                r"   generate_persona_for_storez3PersonaGenerationService.generate_persona_for_store   s   &H	#99(IN .88
  ('//x||/D
%-\\(,,%?*%L$R$R!$q(!;; $ F!99:JK  "&!=!=h	!R%77!U !%!>!>?QSb!c#'#B#B>#R  44)%57GG
 GGNN33811':),-?)@%4$,LL$>$H$H$J%		 	3  I(SUVYZ[V\U]^_77!A#a&J   KH:UWX[\]X^W_`a77!CCF8L 4  	GGLL>xj3q6(ST334SVH= 	s   B)I ,*I F +G+ <BI 	G(AG#G(I #G((I +	I4AI :I;I  II 	J<A J71J<7J<c                 d   | j                   j                  t              j                  t        j                  |k(        }|r2|j                  t        j
                  |k(        }|j                         S |j                  t        j
                  j                  d            }|j                         S )z&Get existing persona for store/branch.N)r   queryr   filterr%   r&   is_firstr!   r%   r&   rQ   s       r"   r4   z.PersonaGenerationService._get_existing_personaz   s    g&--g.>.>(.JKLL!2!2i!?@E {{} LL!2!2!6!6t!<=E{{}r$   c                 J   | j                   j                  t              j                  t              j                  t        j                  j                  d      t        j                  |k(        }|r"|j                  t        j                  |k(        }|j                         S )z6Get all connected social media accounts for the store.F)r   rQ   r   joinr   rR   
is_deletedrS   r%   r&   allrU   s       r"   r<   z0PersonaGenerationService._get_connected_accounts   sx    ./44]CJJ''++E2%%1

 LL!1!;!;y!HIEyy{r$   rJ   c                    t        j                  t        j                        j	                         }|t        |      z
  }|D cg c]  }|j                   }}	 t        | j                  |||      }|j                  d      st        d|j                  d             	 |d   }	t        j                  d	t        |	j!                                       d
|	v rIt        j                  dt#        |	d
                 t        j                  d|	d
   r|	d
   dd nd        	 t%        j&                  |	j                  di       j                  dd      |	j                  di       j                  dd      |	j                  di       j                  dd      |	j                  di       j                  dd      |	j                  di       j                  dd      |	j                  di       j                  dd      |	j                  d
g       |	j                  dg       |	j                  dg       	      S c c}w # t        $ r=}t        j                  dt        |              t        dt        |             d}~ww xY w# t        $ rI}t        j                  dt        |              t%        j&                  ddddddg g g 	      cY d}~S d}~ww xY w)z=Generate comprehensive analytics data for persona generation.)r9   r-   zFailed to get analytics data: r.   z4Error calling get_social_media_dashboard_analytics: zAnalytics service error: Nr/   zAnalytics data structure: social_networkszSocial networks data type: zSocial networks sample:    Emptyoverall_metricstotal_postsr   total_reactionstotal_commentstotal_sharesengagement_metricspost_impressionspost_engagement_rate        
top_tweetsdaily_metrics)	r_   r`   ra   rb   total_impressionsengagement_rateplatform_breakdown	top_postsrh   z)Error creating SocialMediaAnalyticsData: )r   r8   r	   r7   r   r   idr   r   getr>   r?   r@   rA   infolistkeystyper   SocialMediaAnalyticsData)
r!   rJ   r'   end_date
start_datecaaccount_idsanalytics_resultrL   rK   s
             r"   r=   z1PersonaGenerationService._generate_analytics_data   s   <<-224	 ??
'9:ruu::
	BCj(  $''	2"@AQAUAUV_A`@a bcc 3 *&1 	0n6I6I6K1L0MNO.KK5d>J[;\6]5^_`KK2\jk|\}>BS3TUWVW3X  DK  3L  M  N	22*../@"EII-YZ[ . 2 23Db I M MN_ab c-112CRHLLM]_`a+//0A2FJJ>[\]"0"4"45I2"N"R"RSegh"i . 2 23G L P PQgil m#1#5#56G#L(,,\2>,00"E
 
3 ;  	BLLOPSTUPVxXY7Ax@AA	B2  	LLDSVHMN22 ! "# ##% 
 
	s>   H2AH7 $DJ  7	I= 8I88I= 	K	>KKKrK   c                     | j                  |      }| j                  |      }| j                  |      }| j                  |      }| j	                  |      }t        j                  |||||      S )z.Generate persona insights from analytics data.)content_preferencesaudience_behaviorperformance_patternsgrowth_indicatorsbrand_voice_analysis)_analyze_content_preferences_analyze_audience_behavior_analyze_performance_patterns_analyze_growth_indicators_analyze_brand_voicer   PersonaInsights)r!   rK   rz   r{   r|   r}   r~   s          r"   rB   z3PersonaGenerationService._generate_persona_insights   s     #??O !;;NK  $AA.Q !;;NK  $88H%% 3/!5/!5
 	
r$   c                     | j                  |      | j                  |      | j                  |      | j                  |      | j	                  |      d}|S )z0Analyze content preferences from analytics data.)posting_frequencycontent_typesoptimal_posting_timeshashtag_usagecontent_themes)_calculate_posting_frequency_analyze_content_types_analyze_posting_times_analyze_hashtag_usage_extract_content_themes)r!   rK   preferencess      r"   r   z5PersonaGenerationService._analyze_content_preferences   sY     "&!B!B>!R!88H%)%@%@%P!88H"::>J
 r$   c                     | j                  |      | j                  |      | j                  |      | j                  |      d}|S )z#Analyze audience behavior patterns.)engagement_patternsresponse_timespreferred_contentaudience_segments)_analyze_engagement_patterns_analyze_response_times_analyze_preferred_content_identify_audience_segments)r!   rK   behaviors      r"   r   z3PersonaGenerationService._analyze_audience_behavior   sJ     $(#D#D^#T"::>J!%!@!@!P!%!A!A.!Q	
 r$   c                     | j                  |      | j                  |      | j                  |      | j                  |      d}|S )z(Analyze performance patterns and trends.)engagement_trendsreach_patternsviral_factorsperformance_baselines)_analyze_engagement_trends_analyze_reach_patterns_identify_viral_factors _calculate_performance_baselines)r!   rK   patternss      r"   r   z6PersonaGenerationService._analyze_performance_patterns   sJ     "&!@!@!P"::>J!99.I%)%J%J>%Z	
 r$   c                     | j                  |      | j                  |      | j                  |      | j                  |      d}|S )z%Analyze growth indicators and trends.)follower_growthengagement_growthreach_expansioncontent_evolution)_analyze_follower_growth_analyze_engagement_growth_analyze_reach_expansion_analyze_content_evolution)r!   rK   
indicatorss      r"   r   z3PersonaGenerationService._analyze_growth_indicators  sK      $<<^L!%!@!@!P#<<^L!%!@!@!P	

 r$   c                     | j                  |      | j                  |      | j                  |      | j                  |      d}|S )z,Analyze brand voice and communication style.)tone_characteristicscommunication_stylebrand_personalityvoice_consistency)_analyze_tone_characteristics_analyze_communication_style_identify_brand_personality_assess_voice_consistency)r!   rK   voice_analysiss      r"   r   z-PersonaGenerationService._analyze_brand_voice  sK     %)$F$F~$V#'#D#D^#T!%!A!A.!Q!%!?!?!O	
 r$   c                    |j                   }t        |j                        }|dkD  r||z  nd}|j                  D cg c]G  }|j                  di       j                  dd      |j                  di       j                  dd      z   I }}| j	                  |      }t        |d      ||| j                  |      dS c c}w )z%Calculate posting frequency patterns.r   twitterpostsfacebook_pager\   )average_daily_postsr_   most_active_daysposting_consistency)r_   rE   rh   rn   _find_most_active_daysround_calculate_consistency_score)r!   rK   r_   r1   avg_daily_postsdaydaily_postsr   s           r"   r   z5PersonaGenerationService._calculate_posting_frequency  s    $00N8899F9J+5PQ "0!=!=? wwy"-11'1=Y[@\@`@`ahjk@ll ? ?  66{C $)!#<& 0#'#D#D[#Q	
 	
?s   AB;c                     ddddddS )z"Analyze content types and formats.r   )
text_postsimage_postsvideo_posts
link_postsmixed_content r!   rK   s     r"   r   z/PersonaGenerationService._analyze_content_types)  s    
 
 	
r$   c                     g dg ddi dS )zAnalyze optimal posting times.)Monday	WednesdayFriday)	            UTC)	best_days
best_hoursr	   performance_by_timer   r   s     r"   r   z/PersonaGenerationService._analyze_posting_times5  s     ;)#%	
 	
r$   c           	         g }|j                   D ];  }|j                  dd      }t        j                  d|      }|j	                  |       = t        |      }|j                  d      }t        |      t        t        |            |D 	cg c]
  \  }}	||	d c}	}|j                  dkD  rt        |      |j                  z  dS ddS c c}	}w )zAnalyze hashtag usage patterns.content z#\w+
   )tagcountr   )total_hashtagsunique_hashtagstop_hashtagshashtag_frequency)
rl   rn   refindallextendr   most_commonrE   setr_   )
r!   rK   hashtagspostr   post_hashtagshashtag_countsr   r   r   s
             r"   r   z/PersonaGenerationService._analyze_hashtag_usage?  s     ",, 	+Dhhy"-GJJw8MOOM*	+
 !*%11"5 "(m"3x=1LXYjc5S59YO]OiOilmOmX1K1K!K	
 	
 tu	
 	
 Zs   C

c                 .    ddddddddddddddddgS )	z"Extract content themes from posts.zCustomer Servicehigh)theme	frequency
engagementzProduct UpdatesmediumzCommunity Engagement
Promotionslowr   r   s     r"   r   z0PersonaGenerationService._extract_content_themesR  s7    
 )vVT'hhW,6QWX"hO	
 	
r$   c           
      F   i }|j                   D ]  }|j                  dd      }|j                  dd      |j                  dd      |j                  dd      |j                  dd      |j                  dd      |j                  d	d
      d||<    |j                  |dg dS )zAnalyze engagement patterns.networkunknownr   r   	reactionscommentssharesimpressionsrj   rf   )r   r   r   r   r   rj   
increasing)average_engagement_rateengagement_by_platformr   peak_engagement_times)rk   rn   rj   )r!   rK   platform_engagementplatform_datar   s        r"   r   z5PersonaGenerationService._analyze_engagement_patterns]  s     !+>> 		M#''	9=G&**7A6*..{A>)--j!<'++Ha8,00B#0#4#45F#L,(		 (6'E'E&9!-%'	
 	
r$   c                     ddddS )z0Analyze response times to audience interactions.z2 hours333333?r   )average_response_timeresponse_rateresponse_qualityr   r   s     r"   r   z0PersonaGenerationService._analyze_response_timess  s     &/! &
 	
r$   c                     ddgddgdg ddS )z*Analyze what content the audience prefers.imagesvideoszproduct updateszbehind the scenesr   )likesr   r   )high_performing_formatspreferred_topicscontent_length_preferenceinteraction_typesr   r   s     r"   r   z3PersonaGenerationService._analyze_preferred_content{  s%     )1(';!24G H)1!@	
 	
r$   c                 0    ddddgddddd	gdd
dddgdgS )z%Identify different audience segments.zEngaged Followers   zhigh engagementzregular interaction)segment
percentagecharacteristicszPassive Followers<   zlow engagementzoccasional interactionzBrand Advocatesr   zhigh sharingzpositive sentimentr   r   s     r"   r   z4PersonaGenerationService._identify_audience_segments  sA     ,2Sdf{R|}+2Sce}R~)Q_auPvw
 	
r$   c                     ddg ddS )z$Analyze engagement trends over time.r   333333?stable)trend_directiongrowth_rateseasonal_patternstrend_stabilityr   r   s     r"   r   z3PersonaGenerationService._analyze_engagement_trends  s      ,!#'	
 	
r$   c                 f    |j                   dkD  r|j                  |j                   z  ndddddddS )z&Analyze reach and impression patterns.r   Q?g333333?r  r  )organicpaid)average_reachreach_growthviral_coefficientorganic_vs_paid)r_   ri   r   s     r"   r   z0PersonaGenerationService._analyze_reach_patterns  sG     _m^x^x{|^|^==@Z@ZZ  CD !$+/>	
 	
r$   c                 .    ddddddddddd	dd
dddgS )z2Identify factors that contribute to viral content.zEmotional appealr   z#Content that evokes strong emotions)factorimpactdescriptionzTimely contentz+Content related to current events or trendszUser-generated contentr   z%Content created by users or communityzTrending topicsz'Content about popular or viral subjectsr   r   s     r"   r   z0PersonaGenerationService._identify_viral_factors  s:     *VLqr'6Jwx/8T{|(HMvw	
 	
r$   c                 t    |j                   |j                  dkD  r|j                  |j                  z  nddddS )z Calculate performance baselines.r   r  g?)engagement_rate_baselinereach_baselineresponse_rate_baselinegrowth_rate_baseline)rj   r_   ri   r   s     r"   r   z9PersonaGenerationService._calculate_performance_baselines  sF     )7(F(F_m_y_y|}_}n>>A[A[[  DE&*$(	
 	
r$   c                     ddg g ddS )z!Analyze follower growth patterns.g{Gz?r  )zcontent qualityr   consistency)r  growth_consistencypeak_growth_periodsgrowth_factorsr   r   s     r"   r   z1PersonaGenerationService._analyze_follower_growth  s      "*#%N	
 	
r$   c                     ddddS )z#Analyze engagement growth patterns.r  r   r  )engagement_growth_ratequality_improvementaudience_maturationr   r   s     r"   r   z3PersonaGenerationService._analyze_engagement_growth  s     '+#/#+
 	
r$   c                     ddddS )z!Analyze reach expansion patterns.r  growingzlocal focus)reach_growth_rateaudience_expansiongeographic_spreadr   r   s     r"   r   z1PersonaGenerationService._analyze_reach_expansion  s     "&"+!.
 	
r$   c                     ddddS )z*Analyze how content has evolved over time.r   moderate	improving)content_sophisticationformat_innovationaudience_alignmentr   r   s     r"   r   z3PersonaGenerationService._analyze_content_evolution  s     '3!+"-
 	
r$   c                     dddddS )z*Analyze tone characteristics of the brand.friendlyr   positivecasual)primary_tonetone_consistencyemotional_rangeformality_levelr   r   s     r"   r   z6PersonaGenerationService._analyze_tone_characteristics  s     ' &)'	
 	
r$   c                     dddddS )zAnalyze communication style.conversationalr   genuiner<  )styleapproachabilityauthenticitytransparencyr   r   s     r"   r   z5PersonaGenerationService._analyze_communication_style  s     &%%&	
 	
r$   c                     g dg dddS )z"Identify brand personality traits.)rB  professional
innovativereliable)qualityzcustomer service
innovationr   )personality_traitsbrand_valuespersonality_consistencyr   r   s     r"   r   z4PersonaGenerationService._identify_brand_personality  s     #YI'-
 	
r$   c                     ddddS )z*Assess voice consistency across platforms.r   r  strong)cross_platform_consistencytemporal_consistencycontent_alignmentr   r   s     r"   r   z2PersonaGenerationService._assess_voice_consistency  s     +1$,!)
 	
r$   r   c                 ,    g d}ddddddddddd	dgS )
z"Find the most active posting days.)r   Tuesdayr   Thursdayr   SaturdaySundayr   r   r,   )r   activity_levelr   r   r   r   r\   r   )r!   r   days_of_weeks      r"   r   z/PersonaGenerationService._find_most_active_days  s1    e C6AF1E
 	
r$   c                     |syt        |      t        |      z  t        fd|D              t        |      z  }|dz  }dkD  rt        dd|z  z
        nd}t        |d      S )z$Calculate posting consistency score.rf   c              3   .   K   | ]  }|z
  d z    yw)r\   Nr   ).0x
mean_postss     r"   	<genexpr>zHPersonaGenerationService._calculate_consistency_score.<locals>.<genexpr>  s     BJ1,Bs   g      ?r      r\   )sumrE   maxr   )r!   r   variancestd_devconsistency_scoreri  s        @r"   r   z5PersonaGenerationService._calculate_consistency_score  sr    %K(88
BkBBSEUUc/ CMq.C1*(<#=>VW&**r$   rH   insightsc           
      X   |r+t        j                  t        j                        |_        |}nt        ||d| ddt        j                  t        j                        t        j                  t        j                              }| j                  j                  |       | j                  j                          | j                  |j                  |       | j                  |j                  |       | j                  |j                  |       | j                  |j                  |       |S )z1Create or update persona with generated insights.Store__Personaactive)r%   r&   namestatus
created_atr5   )r   r8   r	   r7   r5   r   r   addflush_create_or_update_profilerm   _create_or_update_audience_create_or_update_context_create_or_update_performance)r!   r%   r&   rH   rq  rN   s         r"   rC   z2PersonaGenerationService._create_or_update_persona
  s     *2,,x||*D'&G !#hZx0#<<5#<<5G GGKK GGMMO 	&&wzz8< 	''

H= 	&&wzz8< 	**7::x@r$   
persona_idc                    | j                   j                  t              j                  t        j                  |k(        j                         }|s't        |      }| j                   j                  |       | j                  |      |_        | j                  |      |_
        | j                  |      |_        | j                  |      |_        | j                  |      |_        | j#                  |      |_        y)z!Create or update persona profile.r  N)r   rQ   r   rR   r  rT   ry  _generate_brand_summarybrand_summary_generate_voice_rulesvoice_rules_generate_goalsgoals_identify_competitorscompetitors_identify_brand_assetsbrand_assets_identify_constraintsconstraints)r!   r  rq  profiles       r"   r{  z2PersonaGenerationService._create_or_update_profile2  s    ''--/66~7P7PT^7^_eeg$
;GGGKK  !% < <X F"88B,,X6"88B#::8D"88Br$   c                 H   | j                   j                  t              j                  t        j                  |k(        j                         }|s't        |      }| j                   j                  |       | j                  |      |_        | j                  |      |_
        y)z"Create or update persona audience.r  N)r   rQ   r   rR   r  rT   ry  _analyze_localeslocales_analyze_languages	languages)r!   r  rq  audiences       r"   r|  z3PersonaGenerationService._create_or_update_audienceB  sy    77==1889S9SWa9abhhj&*=HGGKK!  00:!44X>r$   c                    | j                   j                  t              j                  t        j                  |k(        j                         }|s't        |      }| j                   j                  |       |j                  j                  di       |_	        |j                  j                  dg       |_
        |j                  j                  di       |_        |j                  j                  di       |_        | j                  |      |_        | j                  |      |_        | j#                  |      |_        t'        j(                  t*        j,                        |_        y)z!Create or update persona context.r  r   r   r   r   N)r   rQ   r   rR   r  rT   ry  rz   rn   content_categoriesr   hashtag_strategyposting_cadence_generate_narrative_brandnarrative_brand_generate_narrative_audiencenarrative_audience_generate_narrative_voicenarrative_voicer   r8   r	   r7   r5   )r!   r  rq  contexts       r"   r}  z2PersonaGenerationService._create_or_update_contextN  s   ''--/66~7P7PT^7^_eeg$
;GGGKK  &.%A%A%E%EoWY%Z"!)!=!=!A!ABRTV!W#+#?#?#C#COUW#X "*">">"B"BCVXZ"["&"@"@"J%)%F%Fx%P""&"@"@"J%\\(,,7r$   c                    | j                   j                  t              j                  t        j                  |k(        j                         }|s't        |      }| j                   j                  |       |j                  j                  di       |_	        |j                  |_        |j                  j                  dg       |_        |j                  j                  dg       |_        |j                  j                  di       |_        |j                  j                  di       j                  dg       |_        |j                  j                  di       |_        y	)
z%Create or update persona performance.r  r   r   r   r   r   r   r   N)r   rQ   r   rR   r  rT   ry  r|   rn   engagement_datar}   growth_metricsbest_performing_postsr{   	interestsrz   best_posting_windowsbest_hashtags	baselines)r!   r  rq  performances       r"   r~  z6PersonaGenerationService._create_or_update_performance`  s   ggmm$67>>?Q?\?\`j?jkqqs,
CKGGKK$ '/&C&C&G&GH[]_&`#%-%?%?",4,I,I,M,Mo_a,b) ( : : > >?RTV W+3+G+G+K+KLceg+h($,$@$@$D$D_VX$Y$]$]^lnp$q! ( = = A ABY[] ^r$   c                     |j                   j                  di       }|j                   j                  di       }d|j                  dd       d|j                  ddg      d	    d
S )z%Generate brand summary from insights.r   r   zA rE  rQ  z brand with a rV  rS  r   za personality, focused on delivering quality content and engaging with our audience authentically.r~   rn   )r!   rq  voicepersonalitys       r"   r  z0PersonaGenerationService._generate_brand_summaryq  s    --112H"M33778KRPEIInn=>n[__]qt~s  NA  BC  ND  ME  Ef  g  	gr$   c                    |j                   j                  di       j                  dd      |j                   j                  di       j                  dd      |j                   j                  di       j                  dg       g d	d
S )z#Generate voice rules from insights.r   rE  rQ  r   rL  rJ  r   rV  )znegative languagejargonzoverly formal tone)tonerL  r  
do_not_user  r!   rq  s     r"   r  z.PersonaGenerationService._generate_voice_rulesx  s     11556LbQUUVdftu22667LbQUUV]_op#88<<=PRTUYYZnprsO	
 	
r$   c                     dddddS )zGenerate goals from insights.z5Increase engagement and build authentic relationshipszExpand reach and grow audiencez.Create valuable, relevant content consistentlyz5Maintain high response rates and quality interactions)primary	secondaryr   r   r   r  s     r"   r  z(PersonaGenerationService._generate_goals  s     O9GQ	
 	
r$   c                 $    ddddddddddddgS )z-Identify potential competitors from insights.zCompetitor Ar   r   )rv  strengthoverlapzCompetitor BzCompetitor Cr   r   r  s     r"   r  z.PersonaGenerationService._identify_competitors  s,     $HM#fM#5I
 	
r$   c                     dd|j                   j                  di       j                  dd      |j                   j                  di       j                  dg       dS )	z$Identify brand assets from insights.z&Consistent color scheme and typographyzProfessional yet approachabler   rL  rJ  r   rW  )visual_identitycontent_styleunique_voicerW  r  r  s     r"   r  z/PersonaGenerationService._identify_brand_assets  sc      H<$99==>SUWX\\]dfvw$99==>QSUVZZ[ikmn	
 	
r$   c                     dddddS )z)Identify brand constraints from insights.z$Must maintain professional standardszAvoid controversial topicszMaintain consistent qualityzRespond within 24 hours)content_limitationstone_boundariesposting_constraintsengagement_rulesr   r  s     r"   r  z.PersonaGenerationService._identify_constraints  s     $J;#@ 9	
 	
r$   c                     dddddddddgS )z)Analyze geographic locales from insights.USP   )countrypctCAr   UK   r   r  s     r"   r  z)PersonaGenerationService._analyze_locales  s"     !,$r.JX\efLghhr$   c                     ddddddgS )z+Analyze language preferences from insights.en_   )langr  esr  r   r  s     r"   r  z+PersonaGenerationService._analyze_languages  s     b)D+CDDr$   c                      y)z'Generate brand narrative from insights.zWe are a customer-focused brand that values quality, innovation, and authentic relationships. Our social media presence reflects our commitment to engaging with our community meaningfully.r   r  s     r"   r  z2PersonaGenerationService._generate_narrative_brand  s     Nr$   c                      y)z*Generate audience narrative from insights.zOur audience consists of engaged professionals who value quality content, authentic communication, and meaningful interactions. They appreciate our consistent voice and reliable engagement.r   r  s     r"   r  z5PersonaGenerationService._generate_narrative_audience  s     Or$   c                     |j                   j                  di       }|j                   j                  di       }d|j                  dd       d|j                  dd       d	S )
z'Generate voice narrative from insights.r   r   zOur voice is rE  rQ  z and rL  rJ  z[, reflecting our commitment to being approachable while maintaining professional standards.r  )r!   rq  r  rL  s       r"   r  z2PersonaGenerationService._generate_narrative_voice  sn    --112H"M--112GLuyyHIuyyY`brOsNt  uP  Q  	Qr$   rN   c                    t        j                  |j                  |j                  |j                  |j
                  |j                  |j                  |j                  |j                  r| j                  |j                        nd|j                  r| j                  |j                        nd|j                  r| j                  |j                        nd|j                  r | j!                  |j                              S d      S )z+Build persona response from database model.N)rm   r%   r&   rv  rw  rx  r5   r  r  r  r  )r   PersonaResponserm   r%   r&   rv  rw  rx  r5   r  _build_profile_responser  _build_audience_responser  _build_performance_responser  _build_context_response)r!   rN   s     r"   r;   z0PersonaGenerationService._build_persona_response  s    %%zz%%''>>))))EL__D00AZ^HOHXHXT2273C3CD^bQXQdQd889L9LMjnEL__D00A
 	
 [_
 	
r$   r  c                     t        j                  |j                  |j                  |j                  |j
                  |j                  |j                        S )z+Build profile response from database model.)r  r  r  r  r  r  )r   PersonaProfileResponser  r  r  r  r  r  )r!   r  s     r"   r  z0PersonaGenerationService._build_profile_response  sI    ,,!//++--++ --++
 	
r$   r  c                 X    t        j                  |j                  |j                        S )z,Build audience response from database model.)r  r  )r   PersonaAudienceResponser  r  )r!   r  s     r"   r  z1PersonaGenerationService._build_audience_response  s'    --$$((
 	
r$   r  c           
          t        j                  |j                  |j                  |j                  |j
                  |j                  |j                  |j                  |j                        S )z+Build context response from database model.)r  r   r  r  seasonal_eventsr  r  r  )
r   PersonaContextResponser  r   r  r  r  r  r  r  )r!   r  s     r"   r  z0PersonaGenerationService._build_context_response  s]    ,,&99"11$55#33#33#33&99#33	
 		
r$   r  c                    t        j                  |j                  |j                  |j                  |j
                  |j                  |j                  |j                  |j                  |j                  |j                  |j                        S )z/Build performance response from database model.)r  sentiment_metricsr  r  r  segmentsr  best_formatsr  	best_ctasr  )r   PersonaPerformanceResponser  r  r  r  r  r  r  r  r  r  r  )r!   r  s     r"   r  z4PersonaGenerationService._build_performance_response  sx    00'77);;&55"-"C"C!++ ))!,!A!A$11%33!++!++
 	
r$   N   Fr    )S__name__
__module____qualname____doc__r   r#   intr   boolr   r:   rO   r   r4   r   r   r<   rs   r=   r   rB   r
   rA   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   floatr   rC   r{  r|  r}  r~  r  r  r  r  r  r  r  r  r  r  r  r  r;   r   r  r  r   r  r  r   r  r  r   r  r  r   r$   r"   r   r      s   W7  $(!#[[ C=[ 	[
 [ 
	)	)[zc hsm W_`gWh 
 
 
Y]^nYo 
64@P;Q 6dg 6lr  mL  mL 6p
9X9X 
]c]s]s 
4	6;Z;Z 	_cdgildl_m 	9X9X ]abegjbj]k F<[<[ `dehjmem`n 9X9X ]abegjbj]k 63R3R W[\_ad\dWe 
6;Z;Z 
_cdgildl_m 
(

V5T5T 

Y]^acf^fYg 


V5T5T 
Y]^acf^fYg 

V5T5T 
Y]^acf^fYg 
&	
f6U6U 	
Z^_cdgildl_mZn 	

6;Z;Z 
_cdgildl_m 
,
f6U6U 
Z^_bdg_gZh 

9X9X 
]abegjbj]k 

&:Y:Y 
^bcghkmphpcq^r 

9X9X 
]abegjbj]k 

f6U6U 
Z^_bdg_gZh 

f6U6U 
Z^_cdgildl_mZn 

v?^?^ 
cghkmphpcq 

v7V7V 
[_`ceh`h[i 

9X9X 
]abegjbj]k 

v7V7V 
[_`ceh`h[i 

9X9X 
]abegjbj]k 

F<[<[ 
`dehjmem`n 

6;Z;Z 
_cdgildl_m 

&:Y:Y 
^bcfhkck^l 

8W8W 
\`adfiai\j 

$s) 
T#s(^@T 
+S	 +e +&& C=& #7+	&
 ((& 
&PCC C6CYCY C 
?S 
?FDZDZ 
?8C 86CYCY 8$_ _vG]G] _"g0F0F g3 g
f.D.D 
cSVh 

(>(> 
4S> 

f.D.D 
dSVX[S[nI] 

v/E/E 
$sTWx. 

f.D.D 
cSVh 
i)?)? iDcSVhDX i
E6+A+A Ed4PSUXPX>FZ E
N&2H2H NS NOV5K5K OPS OQ&2H2H QS Q
w 
6;Q;Q 
 	
~ 	
&B_B_ 	

 
VEcEc 

~ 
&B_B_ 

7I 
fNoNo 
r$   r   r   r%   r&   r'   r(   r)   c                 @    t        |       }|j                  ||||      S )z5Convenience function to generate persona for a store.)r   rO   )r   r%   r&   r'   r(   services         r"   rO   rO     s&     'r*G--h	?Tabbr$   r  ).sqlalchemy.ormr   
sqlalchemyr   r   r   r   r   r	   typingr
   r   r   r   loggingjsonr   collectionsr   r    src.marketing.apps.persona.modelr   r   r   r   r    src.marketing.apps.Account.modelr   r   "src.marketing.apps.Analytics.modelr   r   src.marketing.apps.post.modelr   .src.marketing.apps.Analytics.twitter_analyticsr   src.marketing.apps.personar   	getLoggerr  r?   r   r  r  r:   rO   r   r$   r"   <module>r     s    " ! 8 8 , ,   	 ,  M T : _ -			8	$d
 d
R  $	c	c	c }	c 		c
 	c %%	cr$   