
    	D,jW              	          d dl Z d dlZd dlZ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 d dlmZmZ  ed          Z ej        d	          Zd
gZ G d de          Z G d de          Zd dedededefdZd Zd Zd Zd Z	 	 	 d!defdZ	 	 d"de fdZ!de fdZ"	 	 	 d!de fdZ#	 	 	 d!de fdZ$dedee j                  fdZ%dS )#    N)Optional)parser)relativedelta)utils)	FlagValue)convert_to_datetime_awareis_valid_regexl   posthogis_notc                       e Zd ZdS )InconclusiveMatchErrorN)__name__
__module____qualname__     d/home/rurouni/.local/share/uv/tools/aider-chat/lib/python3.11/site-packages/posthog/feature_flags.pyr   r      s        Dr   r   c                       e Zd ZdZdS )RequiresServerEvaluationa&  
    Raised when feature flag evaluation requires server-side data that is not
    available locally (e.g., static cohorts, experience continuity).

    This error should propagate immediately to trigger API fallback, unlike
    InconclusiveMatchError which allows trying other conditions.
    N)r   r   r   __doc__r   r   r   r   r      s          	Dr   r    keydistinct_idsaltreturnc                     |  d| | }t          t          j        |                    d                                                    d d         d          }|t
          z  S )N.zutf-8      )inthashlibsha1encode	hexdigest__LONG_SCALE__)r   r   r   hash_keyhash_vals        r   _hashr(   )   s_    +++T++H7< 8 899CCEEcrcJBOOHn$$r   c                     t          | d         |d          }t          |           D ]$}||d         k    r||d         k     r
|d         c S %d S )Nr   variant)r   	value_min	value_max)r(   variant_lookup_table)flagr   
hash_valuer*   s       r   get_matching_variantr0   /   sf    tE{Ki@@@J'-- " "---*w{?S2S2S5>!!!4r   c                     g }d}|                      d          pi                      d          pi                      d          pg }|D ]1}||d         dz  z   }|                    |||d         d           |}2|S )	Nr   filtersmultivariatevariantsrollout_percentaged   r   )r+   r,   r   )getappend)feature_flaglookup_tabler+   multivariatesr*   r,   s         r   r-   r-   7   s    LI"&&y117R<<^LLRPRWW  	  !  (< = CC	#)GENSS	
 	
 	
 		r   c           	      l   ||'t          d|                     dd           d          d| vr't          d|                     dd           d          | d         }t          |          d	k    rWt                              d
|                     d                      t          d|                     dd           d          |D ]}||vr|                    |          }|sd||<   t          d| d          |                    d          sd||<   nH	 t          ||||||          }	|	||<   n-# t           $ r }
d||<   t          d| d|
           |
d}
~
ww xY w||         }|t          d| d          |s dS |                     d          }|                     d          }|                     dd          }|rl|j|                    |          }|t          d| d          |dk    rt          ||          S t          d|                     dd           d| d          dS )a/  
    Evaluate a flag dependency property according to the dependency chain algorithm.

    Args:
        property: Flag property with type="flag" and dependency_chain
        flags_by_key: Dictionary of all flags by their key
        evaluation_cache: Cache for storing evaluation results
        distinct_id: The distinct ID being evaluated
        properties: Person properties for evaluation
        cohort_properties: Cohort properties for evaluation

    Returns:
        bool: True if all dependencies in the chain evaluate to True, False otherwise
    Nz$Cannot evaluate flag dependency on 'r   unknownz+' without flags_by_key and evaluation_cachedependency_chainzFlag dependency property for 'z.' is missing required 'dependency_chain' fieldr   z'Circular dependency detected for flag: z'Circular dependency detected for flag ''z!Cannot evaluate flag dependency 'z!' - flag not found in local flagsactiveFz': zFlag dependency 'z' was previously inconclusivevalueoperatorexactzFlag 'z5' was not evaluated despite being in dependency chainflag_evaluates_toz' has invalid operator 'T)r   r7   lenlogdebugmatch_feature_flag_propertiesmatches_dependency_value)propertyflags_by_keyevaluation_cacher   
propertiescohort_propertiesr>   dep_flag_keydep_flag
dep_resultecached_resultflag_keyexpected_valuerB   actual_values                   r   evaluate_flag_dependencyrW   F   s&   " /7$~8<<y3Q3Q~~~
 
 	

 ))${X\\%-K-K{{{
 
 	
   23 !!		QHLL<O<OQQRRR$Whll5)6T6TWWW
 
 	

 ) * *///#''55H !15 .,gggg  
  ||H-- !5:$\22!%B$'&-(,& &
 :D(661 ! ! !9=(64TTTQRTT  !! )6 (OLOOO    	55	 ||E""H\\'**N||J00H N.'++H55(XXXX   ***+NLIII )teY1O1Ottiqttt  
 4s   D66
E  EE c                    t          |t                    rGt          |          dk    r4t          | t                    r| S t          | t                    r|| k    S dS t          |t                    rt          | t                    r|| k    S dS )a  
    Check if the actual flag value matches the expected dependency value.

    This follows the same logic as the C# MatchesDependencyValue function:
    - String variant case: check for exact match or boolean true
    - Boolean case: must match expected boolean value

    Args:
        expected_value: The expected value from the property
        actual_value: The actual value returned by the flag evaluation

    Returns:
        bool: True if the values match according to flag dependency rules
    r   F)
isinstancestrrE   bool)rU   rV   s     r   rI   rI      s      ,$$ .\):):Q)>)>nd++ 	!!,, 	>115 
L$	'	' .J~t,L,L .~-- 5r   c           
         |                      d          pi                      d          pg }d}|pi }|                      d          pi                      d          pi                      d          pg }d |D             }	|D ]h}
	 t          | ||
||||          r4|
                     d          }|r||	v r|}nt          | |          }|pdc S M# t          $ r  t          $ r d}Y ew xY w|rt	          d	          dS )
Nr2   groupsFr3   r4   c                     g | ]
}|d          S )r   r   ).0r*   s     r   
<listcomp>z1match_feature_flag_properties.<locals>.<listcomp>   s    FFFW'%.FFFr   r*   TzGCan't determine if feature flag is enabled or not with given properties)r7   is_condition_matchr0   r   r   )r.   r   rM   rN   rK   rL   flag_conditionsis_inconclusiveflag_variantsvalid_variant_keys	conditionvariant_overrider*   s                r   rH   rH      s    xx	**0b55h??E2OO)/Rhhy))/R44^DDJOO  	  GFFFF$ # #		# "!   ' $-==#;#; # F(8<N(N(N.GG24EEG$&&&' ( 	 	 	% 	# 	# 	# #OOO	#
  
$U
 
 	
 5s   ACC('C(c           	         |                     d          }t          |                     d          pg           dk    r||                     d          D ]b}|                     d          }	|	dk    rt          ||||||          }
n+|	dk    rt          ||||||          }
nt	          ||          }
|
s dS c|dS |t          | d	         |          |d
z  k    rdS dS )Nr5   rM   r   typecohortr.   FTr   r6   )r7   rE   match_cohortrW   match_propertyr(   )r9   r   rf   rM   rN   rK   rL   r5   propproperty_typematchess              r   ra   ra     s,    #';<<
9==&&,"--11MM,// 	 	D HHV,,M((&% $  &((2 $%  )z:: uu %4%%U0C[*Q*QS + + u4r   c                    |                      d          }|                      d          pd}|                      d          }||vrt          d          |dk    rt          d          ||         }|t          vr|dS |d	v r"d
 }|dk    r |||          S  |||           S |dk    r||v S |dk    rt          j        ||          S |dk    rt          j        ||           S |dk    r_t          t          |                    oBt          j        t          |                    	                    t          |                    d uS |dk    r_t          t          |                    oBt          j        t          |                    	                    t          |                    d u S |dv rd }d }	 t          |          }n# t          $ r Y nw xY w|>|<t          |t                    r ||t          |          |          S  ||||          S  |t          |          t          |          |          S |dv r	 t          t          |                    }	|	s0t          j        t          |                    }	t!          |	          }	n"# t          $ r}
t          d          |
d }
~
ww xY w|	st          d          t          |t"          j                  r!t!          |          }|dk    r||	k     S ||	k    S t          |t"          j                  r6|dk    r||	                                k     S ||	                                k    S t          |t                    rS	 t          j        |          }t!          |          }|dk    r||	k     S ||	k    S # t          $ r t          d          w xY wt          d          t          d|           )Nr   rB   rC   rA   z5can't match properties without a given property value
is_not_setz/can't match properties with operator is_not_setF)rC   r   c                     t          | t                    r-t          |                                          d | D             v S t	          j        | |          S )Nc                 P    g | ]#}t          |                                          $S r   )rZ   casefold)r_   vals     r   r`   z?match_property.<locals>.compute_exact_match.<locals>.<listcomp>W  s7     : : :,/CHH%%'': : :r   )rY   listrZ   rt   r   str_iequals)rA   override_values     r   compute_exact_matchz+match_property.<locals>.compute_exact_matchU  sf    %&& >**3355 : :38: : :   $UN;;;r   is_set	icontainsnot_icontainsregex	not_regex)gtgteltltec                     |dk    r| |k    S |dk    r| |k    S |dk    r| |k     S |dk    r| |k    S t          d|           )Nr   r   r   r   zInvalid operator: )
ValueError)lhsrhsrB   s      r   comparezmatch_property.<locals>.comparey  sm    4Sy U""cz!T!!Sy U""cz! !@h!@!@AAAr   )is_date_beforeis_date_afterz.The date set on the flag is not a valid formatr   z'The date provided is not a valid formatz1The date provided must be a string or date objectzUnknown operator )r7   r   NONE_VALUES_ALLOWED_OPERATORSr   str_icontainsr	   rZ   recompilesearchfloat	ExceptionrY   -relative_date_parse_for_feature_flag_matchingr   parser   datetimedate)rJ   property_valuesr   rB   rA   rx   ry   r   parsed_valueparsed_daterR   override_dates               r   rl   rl   ?  s    ,,u

C||J''27HLL!!E
/!!$C
 
 	
 <$%VWWW$S)N555>;Qu&&&	< 	< 	< w&&un===**5.AAAA8o%%;">5999?""&~u====73u::&& O
3u::&&--c..A.ABB$N	

 ;3u::&& K
3u::&&--c..A.ABBdJ	

 ---
	B 
	B 
	B 	 <<LL 	 	 	D	 #(B.#.. Gw~s5zz8DDDw~|XFFF73~..E

HEEE666		GE

SSK E$l3u::667DD 	 	 	(@ 	
  	(@   nh&788 	5nEEM+++${22${2266 	+++%(8(8(:(:::%(8(8(:(:::,, 	X &^ < < 9- H H///(;66(;66 X X X,-VWWWX )C  
 !!?X!?!?
@
@@s=   :G
 

GGAJ 
J5 J00J5*.N N N9c                     t          |                     d                    }||vrt          d| d          ||         }t          ||||||          S )NrA   zcohort zT not found in local cohorts - likely a static cohort that requires server evaluation)rZ   r7   r   match_property_group)rJ   r   rN   rK   rL   r   	cohort_idproperty_groups           r   rk   rk     sy    " HLL))**I)))&uiuuu
 
 	
 'y1N  r   c           	         | sdS |                      d          }|                      d          }|rt          |          dk    rdS d}d|d         v r|D ]k}		 t          |	|||||          }
|dk    r|
s dS n|
r dS )# t          $ r  t          $ r,}t
                              d|	 d|            d}Y d }~dd }~ww xY w|rt	          d	          |dk    S |D ]}		 |	                     d          d
k    rt          |	|||||          }
n>|	                     d          dk    rt          |	|||||          }
nt          |	|          }
|	                     dd          }|dk    r|
s|s dS |
r|r dS n|
r|s dS |
s|r dS # t          $ r  t          $ r,}t
                              d|	 d|            d}Y d }~d }~ww xY w|rt	          d          |dk    S )NTri   valuesr   FANDzFailed to compute property z
 locally: z8Can't match cohort without a given cohort property valuerj   r.   negationz8can't match cohort without a given cohort property value)
r7   rE   r   r   r   rF   rG   rk   rW   rl   )r   r   rN   rK   rL   r   property_group_typerM   error_matching_locallyrm   ro   rR   r   s                r   r   r     s     t(,,V44##H--J ZA--t":a=   	. 	.D..#% $  '%//" %$uu%  $#tt+   ) . . .		KKKKKLLL)-&&&&&&. " 	(J   #e++  *	. *	.D).88F##x//*')$(# GG XXf%%//6$(#') GG -T?CCG88J66&%//" %8 %$uu %8 %$uu  $x $#tt" $x $#tt+   ) . . .		KKKKKLLL)-&&&&&&. " 	(J  
 #e++sI   A=6A==B="B88B=BF+F2F:FG"F==GrA   c                    d}t          j        ||           }t          j                            t          j        j                  }|rt          |                    d                    }|dk    rd S |                    d          }|dk    r|t          |          z
  }nj|dk    r|t          |          z
  }nP|d	k    r|t          |
          z
  }n6|dk    r|t          |          z
  }n|dk    r|t          |          z
  }nd S |S d S )Nz)^-?(?P<number>[0-9]+)(?P<interval>[a-z])$numberi'  intervalh)hoursd)daysw)weeksm)monthsy)years)	r   r   r   nowtimezoneutcr    groupr   )rA   r}   match	parsed_dtr   r   s         r   r   r   O  s(    9EIeU##E!%%h&7&;<<I U[[**++V4;;z**s??!M$?$?$??II__!Mv$>$>$>>II__!M$?$?$??II__!M$@$@$@@II__!M$?$?$??II4tr   )r   )NNN)NN)&r   r!   loggingr   typingr   dateutilr   dateutil.relativedeltar   r
   r   posthog.typesr   posthog.utilsr   r	   r   r%   	getLoggerrF   r   r   r   r   rZ   r(   r0   r-   rW   rI   rH   r[   ra   rl   rk   r   r   r   r   r   <module>r      s      				             0 0 0 0 0 0       # # # # # # C C C C C C C C())g	""!)
 	 	 	 	 	Y 	 	 			 		 		 		 		y 		 		 		 % %s % %C % % % % %    o o od  L 3 3 3 3 3 3x , , 
, , , ,^@A @A @A @A @AN   
   L h, h, 
h, h, h, h,Vh      r   