o
    @j݁                    @  sh  U d dl mZ d dlZd dlZd dlZd dlZd dlZd dlZd dl	Z	d dl
mZmZ ejdkr6d dl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  d dl!m"Z"m#Z#m$Z$ d dlm%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2 d dl3Z3d dl4m5Z5 d dl6m7Z7m8Z8m9Z9m:Z:m;Z;m<Z<m=Z= d dl>m?Z? d dl@mAZAmBZBmCZC d dlDmEZEmFZFmGZG d dlHmIZI d dlJmKZK d dlLmMZM d dl3mNZNmOZOmPZPmQZQ d dlRmSZS e%rejdkrd dlTaTndaTd dlUaUd dlVaVd dlWmXZX d dlYmZZZ e/deXe9B dZ[ndaVdaTdaUe&Z[ddd Z\dd!d"Z]dd#d$Z^e0ee_e.e0ee_f  f Z`e0ee_e.e0ee_f  f Zaed%Zbd&ecd'< ed%Zdd(ecd)< G d*d+ d+ZeG d,d- d-ZfG d.d/ d/egZhG d0d1 d1ZiG d2d3 d3ZjG d4d5 d5ZkG d6d7 d7ZlG d8d9 d9eZmG d:d; d;e9Zne/d<ZoeNe0eodf eif ZpeNeoejf Zqe/d=erdZseNesekf ZteNeself ZueZveNeoevf Zw	dddEdFZxG dGdH dHe_ZyG dIdJ dJeZzG dKdL dLezZ{G dMdN dNezZ|G dOdP dPezZ}G dQdR dRe}Z~G dSdT dTe}ZG dUdV dVeZG dWdX dXee)eo ZG dYdZ dZeZG d[d\ d\e|eZG d]d^ d^e|eZG d_d` d`eZG dadb dbe|eZG dcdd dde+e_e-e_ f ZG dedf dfeZdddkdlZdddqdrZ	g	g	dddvdwZddgdgddxdd|d}ZdddZdddZdddZ	>	gddddZdddZdddZdddZdddZi d>fdddZdddZdS )    )annotationsN)ABCabstractmethod   	   )BooleanOptionalAction)SUPPRESSArgumentParser	NamespaceRawDescriptionHelpFormatter_SubParsersAction)defaultdictdeque)asdictis_dataclass)Enum)Path)dedent)BuiltinFunctionTypeFunctionTypeSimpleNamespace)TYPE_CHECKINGAnyCallableDictGenericIteratorMappingNoReturnOptionalSequenceTypeVarUnioncastoverload)dotenv_values)AliasChoices	AliasPath	BaseModelJson	RootModelSecretTypeAdapter)Representation)WithArgsTypesorigin_is_uniontyping_base)deep_updateis_model_classlenient_issubclass)is_pydantic_dataclass)	FieldInfo)PydanticUndefined)	Annotated_AnnotatedAliasget_args
get_origin)path_type_labelr      )PydanticDataclass)BaseSettingsPydanticModel)boundreturnNonec               
   C  s>   t d urd S zdd l a W d S  ty }  ztd| d } ~ ww )Nr   zBPyYAML is not installed, run `pip install pydantic-settings[yaml]`)yamlImportErrore rI   h/var/www/www-root/data/www/ai-bot.pdev.uz/venv/lib/python3.10/site-packages/pydantic_settings/sources.pyimport_yamlF   s   
rK   c               
   C  s`   t jdk r$td urd S zdd laW d S  ty# }  ztd| d } ~ ww td ur*d S dd lad S )Nr=   r   zAtomli is not installed, run `pip install pydantic-settings[toml]`)sysversion_infotomlirF   tomllibrG   rI   rI   rJ   import_tomlP   s   

rP   c               
   C  sN   zddl ma ddlma ddlma W d S  ty& }  ztd| d } ~ ww )Nr   )TokenCredential)ResourceNotFoundError)SecretClientzdAzure Key Vault dependencies are not installed, run `pip install pydantic-settings[azure-key-vault]`)azure.core.credentialsrQ   azure.core.exceptionsrR   azure.keyvault.secretsrS   rF   rG   rI   rI   rJ   import_azure_key_vault`   s   rW    PathTypeDEFAULT_PATH
DotenvTypeENV_FILE_SENTINELc                   @     e Zd ZdZdS )NoDecodez0Annotation to prevent decoding of a field value.N__name__
__module____qualname____doc__rI   rI   rI   rJ   r^   y       r^   c                   @  r]   )ForceDecodez.Annotation to force decoding of a field value.Nr_   rI   rI   rI   rJ   re      rd   re   c                   @     e Zd ZdS )SettingsErrorNr`   ra   rb   rI   rI   rI   rJ   rg          rg   c                   @  rf   )_CliSubCommandNrh   rI   rI   rI   rJ   rj      ri   rj   c                   @  rf   )_CliPositionalArgNrh   rI   rI   rI   rJ   rk      ri   rk   c                   @  rf   )_CliImplicitFlagNrh   rI   rI   rI   rJ   rl      ri   rl   c                   @  rf   )_CliExplicitFlagNrh   rI   rI   rI   rJ   rm      ri   rm   c                      s.   e Zd Zdd fdd	Zd fddZ  ZS )_CliInternalArgParserTcli_exit_on_errorboolkwargsr   rC   rD   c                   s   t  jdi | || _d S )NrI   )super__init___cli_exit_on_error)selfro   rq   	__class__rI   rJ   rs      s   
z_CliInternalArgParser.__init__messagestrr   c                   s$   | j s
td| t | d S )Nzerror parsing CLI: )rt   rg   rr   error)ru   rx   rv   rI   rJ   rz      s   z_CliInternalArgParser.error)T)ro   rp   rq   r   rC   rD   )rx   ry   rC   r   )r`   ra   rb   rs   rz   __classcell__rI   rI   rv   rJ   rn      s    rn   c                   @  rf   )CliMutuallyExclusiveGroupNrh   rI   rI   rI   rJ   r|      ri   r|   T_CliBoolFlagTmodelis_requiredrp   ro   bool | NoneOptional[PydanticModel]c           	      C  s   t | }|du rt|r|jd}t|tr|}|du rd}g }t| D ]\}}t|j	v rCt
| |dur>t
| |  S || q'|r]|rQdd| dnd}|rYt|t|dS )a  
    Get the subcommand from a model.

    Args:
        model: The model to get the subcommand from.
        is_required: Determines whether a model must have subcommand set and raises error if not
            found. Defaults to `True`.
        cli_exit_on_error: Determines whether this function exits with error if no subcommand is found.
            Defaults to model_config `cli_exit_on_error` value if set. Otherwise, defaults to `True`.

    Returns:
        The subcommand model if found, otherwise `None`.

    Raises:
        SystemExit: When no subcommand is found and is_required=`True` and cli_exit_on_error=`True`
            (the default).
        SettingsError: When no subcommand is found and is_required=`True` and
            cli_exit_on_error=`False`.
    Nro   Tz#Error: CLI subcommand is required {, }z@Error: CLI subcommand is required but no subcommands were found.)typer3   model_configget
isinstancerp   _get_model_fieldsitemsrj   metadatagetattrappendjoin
SystemExitrg   )	r   r   ro   	model_clsmodel_defaultsubcommands
field_name
field_infoerror_messagerI   rI   rJ   get_subcommand   s*   


r   c                   @  rf   )EnvNoneTypeNrh   rI   rI   rI   rJ   r      ri   r   c                   @  s   e Zd ZdZd(ddZd)d
dZd*ddZed+ddZed,ddZ	e
d-ddZd.ddZd/d!d"Zd0d#d$Ze
d+d%d&Zd'S )1PydanticBaseSettingsSourcezi
    Abstract base class for settings sources, every settings source classes should inherit from it.
    settings_clstype[BaseSettings]c                 C  s   || _ |j| _i | _i | _d S N)r   r   config_current_state_settings_sources_data)ru   r   rI   rI   rJ   rs      s   
z#PydanticBaseSettingsSource.__init__statedict[str, Any]rC   rD   c                 C  
   || _ dS )z
        Record the state of settings from the previous settings sources. This should
        be called right before __call__.
        Nr   )ru   r   rI   rI   rJ   _set_current_state      
z-PydanticBaseSettingsSource._set_current_statestatesdict[str, dict[str, Any]]c                 C  r   )z
        Record the state of settings from all previous settings sources. This should
        be called right before __call__.
        Nr   )ru   r   rI   rI   rJ   _set_settings_sources_data   r   z5PydanticBaseSettingsSource._set_settings_sources_datac                 C     | j S )z`
        The current state of the settings, populated by the previous settings sources.
        r   ru   rI   rI   rJ   current_state      z(PydanticBaseSettingsSource.current_statec                 C  r   )z=
        The state of all previous settings sources.
        r   r   rI   rI   rJ   settings_sources_data  r   z0PydanticBaseSettingsSource.settings_sources_datafieldr6   r   ry   tuple[Any, str, bool]c                 C     dS )a  
        Gets the value, the key for model creation, and a flag to determine whether value is complex.

        This is an abstract method that should be overridden in every settings source classes.

        Args:
            field: The field.
            field_name: The field name.

        Returns:
            A tuple contains the key, value and a flag to determine whether value is complex.
        NrI   ru   r   r   rI   rI   rJ   get_field_value     z*PydanticBaseSettingsSource.get_field_valuerp   c                 C  s   t |j|jS )z
        Checks whether a field is complex, in which case it will attempt to be parsed as JSON.

        Args:
            field: The field.

        Returns:
            Whether the field is complex.
        )_annotation_is_complex
annotationr   )ru   r   rI   rI   rJ   field_is_complex  s   
z+PydanticBaseSettingsSource.field_is_complexvaluer   value_is_complexc                 C  s(   |dur|  |s|r| |||S |S )aF  
        Prepares the value of a field.

        Args:
            field_name: The field name.
            field: The field.
            value: The value of the field that has to be prepared.
            value_is_complex: A flag to determine whether value is complex.

        Returns:
            The prepared value.
        N)r   decode_complex_value)ru   r   r   r   r   rI   rI   rJ   prepare_field_value*  s   z.PydanticBaseSettingsSource.prepare_field_valuec                 C  s6   |rt |jv s| jddu rt|jvr|S t|S )a  
        Decode the value for a complex field

        Args:
            field_name: The field name.
            field: The field.
            value: The value of the field that has to be prepared.

        Returns:
            The decoded value for further preparation
        enable_decodingF)r^   r   r   r   re   jsonloads)ru   r   r   r   rI   rI   rJ   r   ;  s
   

z/PydanticBaseSettingsSource.decode_complex_valuec                 C     d S r   rI   r   rI   rI   rJ   __call__O     z#PydanticBaseSettingsSource.__call__N)r   r   )r   r   rC   rD   )r   r   rC   rD   rC   r   )rC   r   r   r6   r   ry   rC   r   )r   r6   rC   rp   
r   ry   r   r6   r   r   r   rp   rC   r   )r   ry   r   r6   r   r   rC   r   )r`   ra   rb   rc   rs   r   r   propertyr   r   r   r   r   r   r   r   rI   rI   rI   rJ   r      s     





r   c                      sB   e Zd ZdZdd fddZdddZdddZdddZ  ZS )DefaultSettingsSourcea  
    Source class for loading default object values.

    Args:
        settings_cls: The Settings class.
        nested_model_default_partial_update: Whether to allow partial updates on nested model default object fields.
            Defaults to `False`.
    Nr   r   #nested_model_default_partial_updater   c                   s   t  | i | _|d ur|n| jdd| _| jrN|j D ]0\}}t||^}}|d }t	t
|jr>t|j| j|< qtt
|jrM|j | j|< qd S d S )Nr   Fr   )rr   rs   defaultsr   r   r   model_fieldsr   _get_alias_namesr   r   defaultr   r3   
model_dump)ru   r   r   r   r   alias_names_preferred_aliasrv   rI   rJ   rs   ^  s"   zDefaultSettingsSource.__init__r   r6   r   ry   rC   r   c                 C  r   N)NrX   FrI   r   rI   rI   rJ   r   o  r   z%DefaultSettingsSource.get_field_valuer   c                 C  r   r   )r   r   rI   rI   rJ   r   s  s   zDefaultSettingsSource.__call__c                 C     | j j d| j dS )Nz%(nested_model_default_partial_update=))rw   r`   r   r   rI   rI   rJ   __repr__v  s   zDefaultSettingsSource.__repr__r   )r   r   r   r   r   r   rC   ry   	r`   ra   rb   rc   rs   r   r   r   r{   rI   rI   rv   rJ   r   T  s    	

r   c                      sD   e Zd ZdZ	dd fd	d
ZdddZdddZdddZ  ZS )InitSettingsSourcezX
    Source class for loading values provided during settings class initialization.
    Nr   r   init_kwargsr   r   r   c                   s8   || _ t | |d ur|| _d S | jdd| _d S )Nr   F)r   rr   rs   r   r   r   )ru   r   r   r   rv   rI   rJ   rs     s   zInitSettingsSource.__init__r   r6   r   ry   rC   r   c                 C  r   r   rI   r   rI   rI   rJ   r     r   z"InitSettingsSource.get_field_valuec                 C  s$   | j rttttf | jS | jS r   )r   r-   r   ry   r   dump_pythonr   r   rI   rI   rJ   r     s
   zInitSettingsSource.__call__c                 C     | j j d| jdS )Nz(init_kwargs=r   )rw   r`   r   r   rI   rI   rJ   r        zInitSettingsSource.__repr__r   )r   r   r   r   r   r   r   r   r   r   rI   rI   rv   rJ   r   |  s    

r   c                      s\   e Zd Z					d"d# fddZd$ddZd%ddZd&ddZd'ddZd(d d!Z  Z	S ))PydanticBaseEnvSettingsSourceNr   r   case_sensitiver   
env_prefix
str | Noneenv_ignore_emptyenv_parse_none_strenv_parse_enumsrC   rD   c                   s   t  | |d ur|n| jdd| _|d ur|n| jdd| _|d ur(|n| jdd| _|d ur6|n| jd| _|d urF|| _d S | jd| _d S )Nr   Fr   rX   r   r   r   )	rr   rs   r   r   r   r   r   r   r   )ru   r   r   r   r   r   r   rv   rI   rJ   rs     s   	$z&PydanticBaseEnvSettingsSource.__init__r   ry   c                 C  s   | j s| S |S r   )r   lower)ru   r   rI   rI   rJ   _apply_case_sensitive     z3PydanticBaseEnvSettingsSource._apply_case_sensitiver   r6   r   list[tuple[str, str, bool]]c                 C  s4  g }t |jttfr|j }n|j}|rct |trX|D ]:}t |tr7||| |t	|dkr2dndf qt |trVt
t|d }||| |t	|dkrRdndf qn||| |df |rl| jddrtt|jrt|j|jr||| | j| df |S ||| | j| df |S )a  
        Extracts field info. This info is used to get the value of field from environment variables.

        It returns a list of tuples, each tuple contains:
            * field_key: The key of field that has to be used in model creation.
            * env_name: The environment variable name of the field.
            * value_is_complex: A flag to determine whether the value from environment variable
              is complex and has to be parsed.

        Args:
            field (FieldInfo): The field.
            field_name (str): The field name.

        Returns:
            list[tuple[str, str, bool]]: List of tuples, each tuple contains field_key, env_name, and value_is_complex.
           TFr   populate_by_name)r   validation_aliasr'   r(   convert_to_aliaseslistry   r   r   lenr$   r   r   r0   r;   r   _union_is_complexr   r   )ru   r   r   r   v_aliasalias	first_argrI   rI   rJ   _extract_field_info  s.   

(
	z1PydanticBaseEnvSettingsSource._extract_field_infofield_valuesr   c                 C  s   i }|  D ]q\}}d}|j}t|}tt|jr3t|dkr3td|v r3|D ]
}	|	dur2|	} nq(|r:t|ds?|||< q|j  D ]\}
}|j	sW|

 |
 krW|} nqD|s_|||< qt|jtrst|trs| ||||
< q|||
< q|S )ae  
        Replace field names in values dict by looking in models fields insensitively.

        By having the following models:

            ```py
            class SubSubSub(BaseModel):
                VaL3: str

            class SubSub(BaseModel):
                Val2: str
                SUB_sub_SuB: SubSubSub

            class Sub(BaseModel):
                VAL1: str
                SUB_sub: SubSub

            class Settings(BaseSettings):
                nested: Sub

                model_config = SettingsConfigDict(env_nested_delimiter='__')
            ```

        Then:
            _replace_field_names_case_insensitively(
                field,
                {"val1": "v1", "sub_SUB": {"VAL2": "v2", "sub_SUB_sUb": {"vAl3": "v3"}}}
            )
            Returns {'VAL1': 'v1', 'SUB_sub': {'Val2': 'v2', 'SUB_sub_SuB': {'VaL3': 'v3'}}}
        N   r   )r   r   r:   r0   r;   r   r   hasattrr   r   r   r4   r)   r   dict'_replace_field_names_case_insensitively)ru   r   r   valuesnamer   sub_model_fieldr   argsargsub_model_field_namefrI   rI   rJ   r     s4   &
zEPydanticBaseEnvSettingsSource._replace_field_names_case_insensitivelyfield_valuec                 C  sJ   i }|  D ]\}}t|tst|ts|n| |||< qd||< q|S )ze
        Recursively parse values that are of "None" type(EnvNoneType) to `None` type(None).
        N)r   r   r   r   _replace_env_none_type_values)ru   r   r   keyr   rI   rI   rJ   r   '  s   

z;PydanticBaseEnvSettingsSource._replace_env_none_type_valuesc                 C  s  i }| j j D ]\}}z| ||\}}}W n ty1 } ztd| d| jj d|d }~ww z
| ||||}W n t	yV } ztd| d| jj d|d }~ww |d ur| j
d urrt|trk| |}nt|trrd }| jst|tr| ||||< q|||< q|S )Nzerror getting value for field "z" from source ""zerror parsing value for field ")r   r   r   r   	Exceptionrg   rw   r`   r   
ValueErrorr   r   r   r   r   r   r   )ru   datar   r   r   	field_keyr   rH   rI   rI   rJ   r   5  sH   


z&PydanticBaseEnvSettingsSource.__call__)NNNNN)r   r   r   r   r   r   r   r   r   r   r   r   rC   rD   )r   ry   rC   ry   )r   r6   r   ry   rC   r   )r   r6   r   r   rC   r   )r   r   rC   r   r   )
r`   ra   rb   rs   r   r   r   r   r   r{   rI   rI   rv   rJ   r     s    


,
Er   c                      s`   e Zd ZdZ						d%d& fddZd' fddZed(ddZd)d!d"Zd*d#d$Z	  Z
S )+SecretsSettingsSourcezE
    Source class for loading settings values from secret files.
    Nr   r   secrets_dirPathType | Noner   r   r   r   r   r   r   rC   rD   c                   s:   t  |||||| |d ur|| _d S | jd| _d S )Nr  )rr   rs   r   r   r  )ru   r   r  r   r   r   r   r   rv   rI   rJ   rs   ^  s   
$zSecretsSettingsSource.__init__r   c                   s   i }| j du r	|S t| j ttjfr| j gn| j }dd |D }g | _|D ]}| s5td| d q%| j	| q%t
| jsC|S | jD ]}| sUtdt| qFt  S )z4
        Build fields from "secrets" files.
        Nc                 S  s   g | ]}t | qS rI   )r   
expanduser).0prI   rI   rJ   
<listcomp>w      z2SecretsSettingsSource.__call__.<locals>.<listcomp>zdirectory "z" does not existz.secrets_dir must reference a directory, not a )r  r   ry   osPathLikesecrets_pathsexistswarningswarnr   r   is_dirrg   r<   rr   r   )ru   secretssecrets_dirsr  pathrv   rI   rJ   r   m  s"   
 


zSecretsSettingsSource.__call__dir_pathr   	file_namery   rp   Path | Nonec                 C  sB   |  D ]}|j|kr|  S |s|j | kr|  S qdS )af  
        Find a file within path's directory matching filename, optionally ignoring case.

        Args:
            dir_path: Directory path.
            file_name: File name.
            case_sensitive: Whether to search for file name case sensitively.

        Returns:
            Whether file path or `None` if file does not exist in directory.
        N)iterdirr   r   )clsr  r  r   r   rI   rI   rJ   find_case_path  s   
z$SecretsSettingsSource.find_case_pathr   r6   r   r   c                 C  s   |  ||}|d ^}}|D ]H\}}}t| jD ]=}	| |	|| j}
|
s%q|
 rE|s6| jddr8||kr8|}|
 	 ||f    S t
jd|
 dt|
 ddd qqd	||fS )
ag  
        Gets the value for field from secret file and a flag to determine whether value is complex.

        Args:
            field: The field.
            field_name: The field name.

        Returns:
            A tuple contains the key, value if the file exists otherwise `None`, and
                a flag to determine whether value is complex.
        r   r   Fzattempted to load secret file "z" but found a z	 instead.   )
stacklevelN)r   reversedr  r  r   is_filer   r   	read_textstripr  r  r<   )ru   r   r   field_infospreferred_keyr   r  env_namer   secrets_pathr  rI   rI   rJ   r     s"   
z%SecretsSettingsSource.get_field_valuec                 C  r   )Nz(secrets_dir=r   )rw   r`   r  r   rI   rI   rJ   r     r   zSecretsSettingsSource.__repr__NNNNNN)r   r   r  r  r   r   r   r   r   r   r   r   r   r   rC   rD   r   )r  r   r  ry   r   rp   rC   r  r   r   )r`   ra   rb   rc   rs   r   classmethodr  r   r   r{   rI   rI   rv   rJ   r  Y  s    
#r  c                      sz   e Zd ZdZ						d/d0 fddZd1ddZd2ddZd3dd Zd4d"d#Z	d5d6d'd(Z	d7d+d,Z
d8d-d.Z  ZS )9EnvSettingsSourcezN
    Source class for loading settings values from environment variables.
    Nr   r   r   r   r   r   env_nested_delimiterr   r   r   rC   rD   c                   sJ   t  |||||| |d ur|n| jd| _t| j| _|  | _	d S )Nr)  )
rr   rs   r   r   r)  r   r   env_prefix_len_load_env_varsenv_vars)ru   r   r   r   r)  r   r   r   rv   rI   rJ   rs     s   
zEnvSettingsSource.__init__Mapping[str, str | None]c                 C  s   t tj| j| j| jS r   )parse_env_varsr  environr   r   r   r   rI   rI   rJ   r+    r   z EnvSettingsSource._load_env_varsr   r6   r   ry   r   c           
      C  sl   d}|  ||}|d ^}}|D ] \}}}	| j|}|dur0|	s,| jddr.||kr.|} nq|||	fS )aq  
        Gets the value for field from environment variables and a flag to determine whether value is complex.

        Args:
            field: The field.
            field_name: The field name.

        Returns:
            A tuple contains the key, value if the file exists otherwise `None`, and
                a flag to determine whether value is complex.
        Nr   r   F)r   r,  r   r   )
ru   r   r   env_valr"  r#  r   r  r$  r   rI   rI   rJ   r     s   
z!EnvSettingsSource.get_field_valuer   r   r   rp   c           
   
   C  s   |  |\}}| jrt|j|}|du r|n|}|s|rgt|tr#|S |du r5| ||| j}|r3|S dS z	| |||}W n t	yT }	 z
|sJ|	W Y d}	~	nd}	~	ww t|t
ret|| ||| jS |S |durm|S dS )a  
        Prepare value for the field.

        * Extract value for nested field.
        * Deserialize value to python object for complex field.

        Args:
            field: The field.
            field_name: The field name.

        Returns:
            A tuple contains prepared value for the field.

        Raises:
            ValuesError: When There is an error in deserializing value for complex field.
        N)_field_is_complexr   _annotation_enum_name_to_valr   r   r   explode_env_varsr,  r   r  r   r2   )
ru   r   r   r   r   
is_complexallow_parse_failureenum_valenv_val_builtrH   rI   rI   rJ   r     s4   

z%EnvSettingsSource.prepare_field_valuetuple[bool, bool]c                 C  sB   |  |rd}d|fS tt|jrt|j|jrd}d|fS dS )za
        Find out if a field is complex, and if so whether JSON errors should be ignored
        FT)FF)r   r0   r;   r   r   r   )ru   r   r5  rI   rI   rJ   r1  '  s   
z#EnvSettingsSource._field_is_complexFieldInfo | Any | Noner   FieldInfo | Nonec                 C  s   |sdS t |tr|jn|}tt|st |tr/t|D ]}| |||}|r,|  S qdS t|s7t	|r{t
|}| D ];\}}	| |	|D ]0\}
}}
|du sT|rc||ks\||krb|	    S qI| | kss| | kry|	    S qIq?dS )aK  
        Find the field in a sub model by key(env name)

        By having the following models:

            ```py
            class SubSubModel(BaseSettings):
                dvals: Dict

            class SubModel(BaseSettings):
                vals: list[str]
                sub_sub_model: SubSubModel

            class Cfg(BaseSettings):
                sub_model: SubModel
            ```

        Then:
            next_field(sub_model, 'vals') Returns the `vals` field of `SubModel` class
            next_field(sub_model, 'sub_sub_model') Returns `sub_sub_model` field of `SubModel` class

        Args:
            field: The field.
            key: The key (env name).
            case_sensitive: Whether to search for key case sensitively.

        Returns:
            Field if it finds the next field otherwise `None`.
        N)r   r6   r   r0   r;   r/   r:   
next_fieldr3   r5   r   r   r   r   )ru   r   r   r   r   type_type_has_keyfieldsr   r   r   r$  rI   rI   rJ   r;  7  s.     zEnvSettingsSource.next_fieldr,  r   c                   sb  t t|jt}fdd||D }i }| D ]\ }t fdd|D s+q jd }|j	^}	}
}|}|}|
D ]}
||j}t|trW||i }qB
||j}|sd|r|r|rp|\}}nd\}}|rz	|||}W n ty } z
|s|W Y d}~nd}~ww t|tr||vst|tr|| i kr|||< q|S )a  
        Process env_vars and extract the values of keys containing env_nested_delimiter into nested dictionaries.

        This is applied to a single field, hence filtering by env_var prefix.

        Args:
            field_name: The field name.
            field: The field.
            env_vars: Environment variables.

        Returns:
            A dictionary contains extracted values from nested env values.
        c                   s    g | ]\}}}|  j  qS rI   )r)  )r  r   r$  r   rI   rJ   r
  }  s    z6EnvSettingsSource.explode_env_vars.<locals>.<listcomp>c                 3  s    | ]}  |V  qd S r   )
startswith)r  prefix)r$  rI   rJ   	<genexpr>      z5EnvSettingsSource.explode_env_vars.<locals>.<genexpr>N)TT)r4   r;   r   r   r   r   anyr*  splitr)  r;  r   r   
setdefaultr1  r   r  r   )ru   r   r   r,  is_dictprefixesresultr0  env_name_without_prefixr   keyslast_keyenv_vartarget_fieldr   r4  allow_json_failurerH   rI   )r$  ru   rJ   r3  m  sH   



z"EnvSettingsSource.explode_env_varsc                 C     | j j d| jd| jdS )Nz(env_nested_delimiter=, env_prefix_len=r   )rw   r`   r)  r*  r   rI   rI   rJ   r     s   zEnvSettingsSource.__repr__r&  )r   r   r   r   r   r   r)  r   r   r   r   r   r   r   rC   rD   rC   r-  r   r   )r   r6   rC   r8  r   )r   r9  r   ry   r   r   rC   r:  )r   ry   r   r6   r,  r-  rC   r   r   )r`   ra   rb   rc   rs   r+  r   r   r1  r;  r3  r   r{   rI   rI   rv   rJ   r(    s"    



.
67r(  c                      s   e Zd ZdZedddddddfd+ fddZd,ddZedddddd-dd Zd.d!d"Z	d,d#d$Z
d/ fd&d'Zd0d)d*Z  ZS )1DotEnvSettingsSourcezB
    Source class for loading settings values from env files.
    Nr   r   env_fileDotenvType | Noneenv_file_encodingr   r   r   r   r)  r   r   r   rC   rD   c
           
   	     sP   |t kr|n|jd| _|d ur|n|jd| _t |||||||	 d S )NrS  rU  )r\   r   r   rS  rU  rr   rs   )
ru   r   rS  rU  r   r   r)  r   r   r   rv   rI   rJ   rs     s   zDotEnvSettingsSource.__init__r-  c                 C  s   |   S r   )_read_env_filesr   rI   rI   rJ   r+    s   z#DotEnvSettingsSource._load_env_varsFencodingr   ignore_emptyparse_none_str	file_pathr   rX  rp   rY  rZ  c                C  s   t | |pdd}t||||S )Nutf8rX  )r&   r.  )r[  rX  r   rY  rZ  	file_varsrI   rI   rJ   _static_read_env_file  s   	z*DotEnvSettingsSource._static_read_env_filec                 C  s   | j || j| j| j| jdS )NrW  )r_  rU  r   r   r   )ru   r[  rI   rI   rJ   _read_env_file  s   z#DotEnvSettingsSource._read_env_filec                 C  s^   | j }|d u r	i S t|ttjfr|g}i }|D ]}t| }| r,|| 	| q|S r   )
rS  r   ry   r  r  r   r  r  updater`  )ru   	env_filesdotenv_varsrS  env_pathrI   rI   rJ   rV    s   z$DotEnvSettingsSource._read_env_filesr   c                   s   t   }| jddk}| j D ]f\}}|r||v rqd}| jj D ]6\}}| ||D ]'\}}	}||	ksRt	|j
|jsMtt|j
rVt|j
|jrV||	rVd} nq/|r[ nq%|sx|rt|| jrt|t| jd  }
|||
< q|||< q|S )NextraforbidFT)rr   r   r   r   r,  r   r   r   r   r   r   r   r0   r;   r   r?  r   r   )ru   r  is_extra_allowedr$  	env_valueenv_usedr   r   r   field_env_namenormalized_env_namerv   rI   rJ   r     s<   


zDotEnvSettingsSource.__call__ry   c              
   C  s.   | j j d| jd| jd| jd| jd
S )Nz
(env_file=z, env_file_encoding=, env_nested_delimiter=rP  r   )rw   r`   rS  rU  r)  r*  r   rI   rI   rJ   r     s   zDotEnvSettingsSource.__repr__)r   r   rS  rT  rU  r   r   r   r   r   r)  r   r   r   r   r   r   r   rC   rD   rQ  r[  r   rX  r   r   rp   rY  rp   rZ  r   rC   r-  )r[  r   rC   r-  r   r   )r`   ra   rb   rc   r\   rs   r+  staticmethodr_  r`  rV  r   r   r{   rI   rI   rv   rJ   rR    s,    


#rR  c                      s  e Zd ZdZddddddddddddddddejejejej	e
fd fd"d#Zedd%d&Zedd*d&Zedd-d&Zddd.d fd2d&Zedd4d5Zedd6d5Zdd7dd9d5Zdd?d@ZddAdBZddGdHZddIdJZddMdNZddTdUZddVdWZddYdZZedd\d]ZddbdcZddddeZejejejej	e
fddfdgZddpdqZddsdtZddudvZddydzZdd~dZ dddZ!dddZ"ddddZ#dddZ$dddZ%dddZ&  Z'S )CliSettingsSourcea  
    Source class for loading settings values from CLI.

    Note:
        A `CliSettingsSource` connects with a `root_parser` object by using the parser methods to add
        `settings_cls` fields as command line arguments. The `CliSettingsSource` internal parser representation
        is based upon the `argparse` parsing library, and therefore, requires the parser methods to support
        the same attributes as their `argparse` library counterparts.

    Args:
        cli_prog_name: The CLI program name to display in help text. Defaults to `None` if cli_parse_args is `None`.
            Otherwse, defaults to sys.argv[0].
        cli_parse_args: The list of CLI arguments to parse. Defaults to None.
            If set to `True`, defaults to sys.argv[1:].
        cli_parse_none_str: The CLI string value that should be parsed (e.g. "null", "void", "None", etc.) into `None`
            type(None). Defaults to "null" if cli_avoid_json is `False`, and "None" if cli_avoid_json is `True`.
        cli_hide_none_type: Hide `None` values in CLI help text. Defaults to `False`.
        cli_avoid_json: Avoid complex JSON objects in CLI help text. Defaults to `False`.
        cli_enforce_required: Enforce required fields at the CLI. Defaults to `False`.
        cli_use_class_docs_for_groups: Use class docstrings in CLI group help text instead of field descriptions.
            Defaults to `False`.
        cli_exit_on_error: Determines whether or not the internal parser exits with error info when an error occurs.
            Defaults to `True`.
        cli_prefix: Prefix for command line arguments added under the root parser. Defaults to "".
        cli_flag_prefix_char: The flag prefix character to use for CLI optional arguments. Defaults to '-'.
        cli_implicit_flags: Whether `bool` fields should be implicitly converted into CLI boolean flags.
            (e.g. --flag, --no-flag). Defaults to `False`.
        cli_ignore_unknown_args: Whether to ignore unknown CLI args and parse only known ones. Defaults to `False`.
        cli_kebab_case: CLI args use kebab case. Defaults to `False`.
        case_sensitive: Whether CLI "--arg" names should be read with case-sensitivity. Defaults to `True`.
            Note: Case-insensitive matching is only supported on the internal root parser and does not apply to CLI
            subcommands.
        root_parser: The root parser object.
        parse_args_method: The root parser parse args method. Defaults to `argparse.ArgumentParser.parse_args`.
        add_argument_method: The root parser add argument method. Defaults to `argparse.ArgumentParser.add_argument`.
        add_argument_group_method: The root parser add argument group method.
            Defaults to `argparse.ArgumentParser.add_argument_group`.
        add_parser_method: The root parser add new parser (sub-command) method.
            Defaults to `argparse._SubParsersAction.add_parser`.
        add_subparsers_method: The root parser add subparsers (sub-commands) method.
            Defaults to `argparse.ArgumentParser.add_subparsers`.
        formatter_class: A class for customizing the root parser help text. Defaults to `argparse.RawDescriptionHelpFormatter`.
    NTr   r   cli_prog_namer   cli_parse_args)bool | list[str] | tuple[str, ...] | Nonecli_parse_none_strcli_hide_none_typer   cli_avoid_jsoncli_enforce_requiredcli_use_class_docs_for_groupsro   
cli_prefixcli_flag_prefix_charcli_implicit_flagscli_ignore_unknown_argscli_kebab_caser   root_parserr   parse_args_methodCallable[..., Any] | Noneadd_argument_methodadd_argument_group_methodadd_parser_methodadd_subparsers_methodformatter_classrC   rD   c              	     s  |d ur|n	|j dtjd | _|d ur|n|j dd| _|d ur%|n|j dd| _|s8| jdu r6dnd}|| _|d urA|n|j d	d| _|d urO|n|j d
d| _	|	d ur]|	n|j dd| _
|
d urk|
n|j dd| _|d ury|n|j dd| _| jd | _| jr|
ds|
ds|
dd std|
 |  jd7  _|d ur|n|j dd| _|d ur|n|j dd| _|d ur|n|j dd| _|d ur|nd}|s|d urtdt j|d| jd| j|d |d u rt| j
| j|jd u rd nt|j|| jddn|}| j|||||||d |dvrO|du r1tjdd  }nt|ttfsBtdt| | j | !| j"|d d S d S )Nrp  r   rt  Fru  TrD   nullrv  rw  ro   rx  rX   ry  -r   .z'CLI settings source prefix is invalid: rz  r{  r|  zGCase-insensitive matching is only supported on the internal root parser)r)  r   r   r   r   )ro   progdescriptionr  prefix_charsallow_abbrev)r}  r~  r  r  r  r  r  NFr   z>cli_parse_args must be List[str] or Tuple[str, ...], recieved parsed_args)#r   r   rL   argvrp  rt  ru  rs  rv  rw  ro   rx  ry  _cli_flag_prefixr?  endswithreplaceisidentifierrg   rz  r{  r|  rr   rs   rn   rc   r   _connect_root_parserr   r   tupler   r+  _parse_argsr}  )ru   r   rp  rq  rs  rt  ru  rv  rw  ro   rx  ry  rz  r{  r|  r   r}  r~  r  r  r  r  r  rv   rI   rJ   rs   L  s   $
	


zCliSettingsSource.__init__r   c                 C  r   r   rI   r   rI   rI   rJ   r        zCliSettingsSource.__call__r   "list[str] | tuple[str, ...] | boolCliSettingsSource[T]c                C  r   )a  
        Parse and load the command line arguments list into the CLI settings source.

        Args:
            args:
                The command line arguments to parse and load. Defaults to `None`, which means do not parse
                command line arguments. If set to `True`, defaults to sys.argv[1:]. If set to `False`, does
                not parse command line arguments.

        Returns:
            CliSettingsSource: The object instance itself.
        NrI   )ru   r   rI   rI   rJ   r     r   r  ,Namespace | SimpleNamespace | dict[str, Any]c                C  r   )a  
        Loads parsed command line arguments into the CLI settings source.

        Note:
            The parsed args must be in `argparse.Namespace`, `SimpleNamespace`, or vars dictionary
            (e.g., vars(argparse.Namespace)) format.

        Args:
            parsed_args: The parsed args to load.

        Returns:
            CliSettingsSource: The object instance itself.
        NrI   ru   r  rI   rI   rJ   r        )r   r  )list[str] | tuple[str, ...] | bool | None?Namespace | SimpleNamespace | dict[str, list[str] | str] | None%dict[str, Any] | CliSettingsSource[T]c                  s~   |d ur|d urt d|d ur0|du r| ji dS |du r%tjdd  }| j| | j|dS |d ur:| j|dS t  S )Nz/`args` and `parsed_args` are mutually exclusiveFr  Tr   )rg   r+  rL   r  r  r}  rr   r   )ru   r   r  rv   rI   rJ   r     s   
r-  c                 C  r   r   rI   r   rI   rI   rJ   r+    r  z CliSettingsSource._load_env_varsc                C  r   )a  
        Loads the parsed command line arguments into the CLI environment settings variables.

        Note:
            The parsed args must be in `argparse.Namespace`, `SimpleNamespace`, or vars dictionary
            (e.g., vars(argparse.Namespace)) format.

        Args:
            parsed_args: The parsed args to load.

        Returns:
            CliSettingsSource: The object instance itself.
        NrI   r  rI   rI   rJ   r+    r  r  /Mapping[str, str | None] | CliSettingsSource[T]c                  s,  |d u ri S t |ttfrt|}g }| D ]0\}}t |tr)| ||||< q|drG|d urG|dd | }| j	| | }|
| q| j	 D ]}| D ]}||vr^| j||< qSqMdd | D }|rt|td t fdd| D sd	| < tttttf || j| j| j| _| S )
N:subcommand:r   c                 S  s    i | ]\}}| d s||qS )r  )r  )r  r   valrI   rI   rJ   
<dictcomp>)       z4CliSettingsSource._load_env_vars.<locals>.<dictcomp>)r   c                 3  s"    | ]}  d |v r|V  qdS )r  NrI   )r  r   last_selected_subcommandrI   rJ   rA  ,  s     z3CliSettingsSource._load_env_vars.<locals>.<genexpr>z{})r   r   r   varsr   r   _merge_parsed_listr  rD  _cli_subcommandsr   r   rs  maxr   rC  rJ  r.  r$   r   ry   r   r   r,  )ru   r  selected_subcommandsr   r  subcommand_namesubcommand_destr   rI   r  rJ   r+    s>   


parsed_list	list[str]r   ry   %tuple[Optional[type], Optional[type]]c                 C  sr   | j |t}|tu stt|rtdd t|D s"|}||fS |r3t|dks1|d dr3tnt	}||fS )Nc                 s  s0    | ]}|t d urt|ttfvr|V  qd S r   )r   r;   r   r   r  r<  rI   rI   rJ   rA  ?  s    zACliSettingsSource._get_merge_parsed_list_types.<locals>.<genexpr>r   r   [)
_cli_dict_argsr   r   r0   r;   rC  r:   r   r?  ry   )ru   r  r   
merge_typeinferred_typerI   rI   rJ   _get_merge_parsed_list_types8  s   
&z.CliSettingsSource._get_merge_parsed_list_typesc                 C  s  zg }d}|  ||\}}|D ]}}t|ts nu| }|dr.|dr.|dd  }|r| }|drC| |||}d}n>|dsM|drT| ||}n+z	| |||}W n! t	y~ } z||u rk||}| |||}W Y d }~nd }~ww d}|s0|s| |||}q|tu r|d	 W S |t
u rdd| dW S i }	|D ]
}
|	t|
 qt|	W S  ty } z
td
| d| d }~ww )NFr  ]r   ,{Tr   zParsing error encountered for z: )r  r   ry   r!  r?  r  _consume_comma_consume_object_or_array_consume_string_or_numberr  r   r   ra  r   r   dumpsr   rg   )ru   r  r   merged_listis_last_consumed_a_valuer  r  r  rH   merged_dictitemrI   rI   rJ   r  K  sV   


z$CliSettingsSource._merge_parsed_listr  r  r  rp   c                 C  s   |s| d |dd  S )Nz""r   )r   )ru   r  r  r  rI   rI   rJ   r  x  s   
z CliSettingsSource._consume_commac                 C  s   d}| dr	dnd}tdt|D ]6}|| dv r|d7 }q|| dv rH|d8 }|| |krH|dkrH||d |d   ||d d    S qtd| d	)
Nr   r  r   r  )r  r  )r   r  r   zMissing end delimiter "r   )r?  ranger   r   rg   )ru   r  r  countclose_delimconsumedrI   rI   rJ   r  }  s   
z*CliSettingsSource._consume_object_or_arrayr  type[Any] | Nonec           	      C  sz  |t urdnt|}d}|t|k r:|| dkr'|dks$||d  dkr'| }|s0|| dkr0n
|d7 }|t|k s|r@td|d |  }|tt fv rzzt| W n tys   || jkrbd}|d	vrq|dsqd| d}Y nw |	| n=d
d |
ddD \}}|dr|ds|ds|drtd| |d|d}}|	t||i ||d  S )Nr   Fr   r   \r  zMismatched quotesr  )truefalser  c                 s  s    | ]}|V  qd S r   rI   )r  kvrI   rI   rJ   rA    s    z>CliSettingsSource._consume_string_or_number.<locals>.<genexpr>=z1Dictionary key=val parameter is a quoted string: )ry   r   rg   r!  r   floatr  rs  r?  r   rD  r  r   r  )	ru   r  r  r  r  is_find_end_quote
val_stringr   r  rI   rI   rJ   r    s:   $
(z+CliSettingsSource._consume_string_or_numberr   type[BaseModel]r   r6   list[type[BaseModel]]c                 C  s   t |js	|jfnt |j}| jrtdd |D }g }|D ];}t|tfddr3td|j d| t|tfddrFtd|j d| t	t
|sRtt
|rY|t
| q|S )Nc                 S     g | ]
}|t d ur|qS r   r   r  rI   rI   rJ   r
        z5CliSettingsSource._get_sub_models.<locals>.<listcomp>F)is_include_originz.CliSubCommand is not outermost annotation for r  z1CliPositionalArg is not outermost annotation for )r:   r   rt  r  _annotation_contains_typesrj   rg   r`   rk   r3   _strip_annotatedr5   r   )ru   r   r   r   field_types
sub_modelsr<  rI   rI   rJ   _get_sub_models  s   z!CliSettingsSource._get_sub_modelsc                 C  s   t |jv rd}n
t|jv rd}nd S |jtur%t| d|j d| dtjdk rB|j	t
u rD|jd u rFt| d|j d| dd S d S d S )NCliImplicitFlagCliExplicitFlagz
 argument r  z is not of type boolr   z, must have default for python versions < 3.9)rl   r   rm   r   rp   rg   r`   rL   rM   r   r7   default_factory)ru   r   r   r   cli_flag_namerI   rI   rJ   _verify_cli_flag_annotations  s   



z.CliSettingsSource._verify_cli_flag_annotationslist[tuple[str, FieldInfo]]c                 C  sl  g g g }}}t | D ]\}}t|jv rk| s'td|j d| dt||^}}t|dkr@td|j d| ddd t	|j
D }	|	D ]}
t|
sbt|
sbtd|j d| dqL|||f qt|jv r| std	|j d| dt||^}}t|dkrtd	|j d| d|||f q| ||| |||f q|| | S )
Nzsubcommand argument r  z has a default valuer   z has multiple aliasesc                 S  r  r   r  r  rI   rI   rJ   r
    r  z6CliSettingsSource._sort_arg_fields.<locals>.<listcomp>z$ has type not derived from BaseModelzpositional argument )r   r   rj   r   r   rg   r`   r   r   r:   r   r3   r5   r   rk   r  )ru   r   positional_argssubcommand_argsoptional_argsr   r   r   r   r  
field_typerI   rI   rJ   _sort_arg_fields  s4   

z"CliSettingsSource._sort_arg_fieldsr}   c                 C  r   )z#The connected root parser instance.)_root_parserr   rI   rI   rJ   r}    s   zCliSettingsSource.root_parserparser_methodmethod_namerq   Callable[..., Any]c                   s^   d ur j du r  dkr tjtr 	 	 ddfdd}|S d u r-d fdd}|S S )NFr~  r}  rn   r   "list[str] | tuple[str, ...] | None	namespaceNamespace | NonerC   r   c                   sv   g }|rt t |ng D ]&}dj d}td| d|}|r/|d |d }|| q | ||S )Nr  z{1,2}z^(z[^\s=]+)(.*)r   r   )	shlexrD  r   ry  rematchgroupr   r   )r}  r   r  insensitive_argsr   flag_prefixmatched)r  ru   rI   rJ   parse_args_insensitive_method  s   zOCliSettingsSource._connect_parser_method.<locals>.parse_args_insensitive_methodrq   c                    s   t d  d)Nz0cannot connect CLI settings source root parser: z. is set to `None` but is needed for connecting)rg   r   rq   )r  rI   rJ   none_parser_method  s   
zDCliSettingsSource._connect_parser_method.<locals>.none_parser_method)NN)r}  rn   r   r  r  r  rC   r   )r   r   rq   r   rC   r   )r   r   r  rn   )ru   r  r  r   rq   r  r  rI   )r  r  ru   rJ   _connect_parser_method  s   

z(CliSettingsSource._connect_parser_methodc                   s   |  |d d fdd}|S )	Nr  parserr   rq   rC   c                   sx     ds  d | fi  S  fdddD }|d  d7  < | fi |}t|ds4td	|jd
i  S )N _is_cli_mutually_exclusive_grouprequiredc                   s    i | ]}| v r|  |qS rI   )popr  r   rq   rI   rJ   r    r  zUCliSettingsSource._connect_group_method.<locals>.add_group_method.<locals>.<dictcomp>)titler  r  z (mutually exclusive)add_mutually_exclusive_groupzcannot connect CLI settings source root parser: group object is missing add_mutually_exclusive_group but is needed for connectingrI   )r  r   rg   r   )r  rq   main_group_kwargsr  add_argument_groupr  rJ   add_group_method  s   


zACliSettingsSource._connect_group_method.<locals>.add_group_method)r  r   rq   r   rC   r   )r  )ru   r  r  rI   r  rJ   _connect_group_method  s   z'CliSettingsSource._connect_group_methodc           	   
   C  s   ddd}|| _ |d u r| jr|ntj}| |d| _| |d	| _| || _| |d
| _	| |d| _
|| _i | _tt| _| j| j| jg | j| jd g td d S )Nr   r   rq   rC   r   c                  _  s   t j| i |d S Nr   )r
   parse_known_argsr  rI   rI   rJ   _parse_known_args0  s   zACliSettingsSource._connect_root_parser.<locals>._parse_known_argsr~  r  r  r  r  r   
added_args
arg_prefixsubcommand_prefixr  alias_prefixesr   )r   r   rq   r   rC   r   )r  r{  r
   
parse_argsr  r  _add_argumentr  
_add_group_add_parser_add_subparsers_formatter_classr  r   r   r  _add_parser_argsr}  r   r   r7   )	ru   r}  r~  r  r  r  r  r  r  rI   rI   rJ   r  &  s,   



z&CliSettingsSource._connect_root_parserr  r
  r  r  r  r  r   r
   c	                   s  d }	i }
t t|stt|rtt||sd n|}| |D ]\}}| |||}t|||
| jd\}}|d }t|j	v r|D ]}| 
t|dkrO|jn|}| | }| | }|| j| d |< t|dkrpd n|j}| jr|jd u r}d nt|j}|	d u r| j|d| dt|dkr|jnd dn|	}	t|	dr|	jr|	jd d  d	| d
nd| d
|	_| j| j|	||| j|jd u rd nt|jd|g | | d| | dd g td qBq | j t|jttttt fdd}|o| }i }t!|d< | "||||d< | #|j|d< | j$o|% o|tu |d< |r7|j&d ur7|s7| | | j'd  n| | |d< | (|||||}|rR|d |v rSq |rmd|d< t|jtt fddrm|j| j)|d < t*|j	v r| 
|+ |d< |d g}|d= |d= d | ,||| |r| j-|||||| ||||||d q |s|d urt.|tr| j/|fi |}|t|7 }| j0|g fdd|D R i | q |t|7 }| j0|g fdd|D R i | q | 1||
|||| |S )N)alias_path_argsr   r   r   r  r   )r  destr  metavarr  r  r   r  )helpr  r  r  r	  T)is_strip_annotatedr   r  r  r  r   actionrX   )r   c                 3  (    | ]} d t |  | V  qd S r   r   r  r   r  rI   rJ   rA       & z5CliSettingsSource._add_parser_args.<locals>.<genexpr>c                 3  r  r   r  r  r  rI   rJ   rA    r  )2r3   r   r5   
issubclassr  r  r   r   rj   r   _check_kebab_namer   r`   r  r  rw  rc   r   r  r   r  r  r  r  r7   r  r  r   r   setr   r!   r   CLI_SUPPRESS_help_format_metavar_formatrv  r   r   r*  _get_arg_namesr  rk   upper_convert_bool_flag_add_parser_submodelsr   r  r  _add_parser_alias_paths)ru   r  r   r
  r  r  r  r  r   
subparsersr  r   r   r  r   is_alias_path_onlyr   subcommand_aliasr  r  subcommand_helpis_append_actionis_parser_submodelrq   	arg_namesrI   r  rJ   r  I  s   




	

/



(z"CliSettingsSource._add_parser_argsr   c                 C  s   | j r	|ddS |S )Nr   r  )r|  r  )ru   r   rI   rI   rJ   r!    s   z#CliSettingsSource._check_kebab_namec                 C  s   |d dkrEd }|j tur|j }|tur|}tjdks t|trG| js(t|jv rKt	|jvrI|d= tjdkr7t
n	dt|   |d< d S d S d S d S d S )Nr  rp   r   store_r  )r   r7   rL   rM   r   rp   rz  rl   r   rm   r   ry   r   )ru   rq   r   r   r   rI   rI   rJ   r(    s    

 
z$CliSettingsSource._convert_bool_flagr   tuple[str, ...]c           
   	   C  sf   g }|g| D ])}|D ]$}|  || jkr| | n
||dd | }	|	|vr/||	 qq|S )NrX   r   )r!  r   r  r   )
ru   r  r  r  r   r
  r1  r@  r   arg_namerI   rI   rJ   r&    s   

z CliSettingsSource._get_arg_namesr  r  r1  c                   s  t |tr	tdd }i }|d  d|d< |j|d< |	d |d< tdd |D |d	< |d	 r:t|d
kr:td| jrUt|d
krU|d jd u rLd nt|d j|d< |t	urkt
t|sett|rjt||
}n|jt	urt|j}n|jd ur||j}|d u rd| j d}|d d urt| d|d  |d< n||d< |d }| js||d  d|d  d|	d< | j|fi |}| j|gfdd|D R i |	 |D ]#}| j|||  | d||r|n| fdd|d
d  D |d qd S )Nz8cannot have nested models in a CliMutuallyExclusiveGroupr   z optionsr  r  r  c                 s      | ]}t |tV  qd S r   )r   r|   )r  r   rI   rI   rJ   rA    s    

z:CliSettingsSource._add_parser_submodels.<locals>.<genexpr>r  r   z/cannot use union with CliMutuallyExclusiveGroupz	default: z (undefined)
zset z from JSON stringr  c                 3  s    | ]	}  | V  qd S r   rI   r  r  rI   rJ   rA  ;  s    r  c                   s   g | ]	}  | d qS )r  rI   r  )r  rI   rJ   r
  D  s    z;CliSettingsSource._add_parser_submodels.<locals>.<listcomp>r	  )r   r|   rg   r  rC  r   rw  rc   r   r7   r3   r   r5   r   r   r  rs  ru  r   r  r  r  )ru   r  r   r  r
  r  r  r  r1  rq   r   r   r   r   model_groupmodel_group_kwargsdesc_headerr   rI   )r  r  rJ   r)    sZ   

$


&
z'CliSettingsSource._add_parser_submodelsr  dict[str, str]c                 C  s  |r|}|d urt |tr| j|fi |n|}|d}|r%|d d n|}| D ]_\}	}
|r3dn|	}	|| jkr@| |	 n
||dd |	 }i }t|d< d|d< | |	 |d< |
d	ksc|rhd	|d
< nd|d< d|d
< ||vr|| | j	|| j
 | fi | q+d S d S )Nr  r  rX   r   r   zpydantic alias pathr  r  r   r  r   r  r   )r   r   r  r  r   r   r  r#  r   r  r  )ru   r  r  r
  r  r  r  contextis_nested_alias_pathr   r  r4  rq   rI   rI   rJ   r*  H  s4   	 



z)CliSettingsSource._add_parser_alias_pathsobjc                 C  s$   | j st|S tdd t|D S )Nc                 S  r  r   r  r  rI   rI   rJ   r
  o  r  z8CliSettingsSource._get_modified_args.<locals>.<listcomp>)rt  r:   r  ru   r=  rI   rI   rJ   _get_modified_argsk  s   z$CliSettingsSource._get_modified_argsobj_qualnamec                 C  sx   d|v r|d | dd  dd || dd d  D  }d|}|r.| d| dS t|dkr6|S d| d	S )
NJSONr   c                 S  s   g | ]}|d kr|qS )rA  rI   r  rI   rI   rJ   r
  s  r  z=CliSettingsSource._metavar_format_choices.<locals>.<listcomp>r  r  r  r  r   )indexr   r   )ru   r   r@  r  rI   rI   rJ   _metavar_format_choicesq  s   6
z)CliSettingsSource._metavar_format_choicesc                 C  sj  t |}t|rd|jv r|jS |jS |du rdS t|tr"t|S t|tjr,t	|S t|t
ttfs7|j}tt|rK| tt| j| |S t|tjtjfv rb| ttt	| |S t|trq| dd |D S t|tr| jtt| j| |t|dr|jdS t	|dS |tdu r| jS t|rd	S t|tr|jS t|d
dddS )z\Pretty metavar representation of a type. Adapts logic from `pydantic._repr.display_as_type`.z<locals>.z...c                 S     g | ]}|j qS rI   r   r  r  rI   rI   rJ   r
        z=CliSettingsSource._metavar_format_recurse.<locals>.<listcomp>rb   )r@  NrA  ztyping.rX   ztyping_extensions.)r  _is_functionrb   r`   r   r.   reprtyping_extensionsTypeAliasTypery   r1   r/   r   rw   r0   r;   rC  r   map_metavar_format_recurser?  Literaltypingr4   r   r   rs  r3   r  r>  rI   rI   rJ   rM  z  s>   



z)CliSettingsSource._metavar_format_recursec                 C  s   |  |ddS )Nr   r  )rM  r  r>  rI   rI   rJ   r%    r   z!CliSettingsSource._metavar_formatc                 C  sd  |j r|j nd}|tkst|jv rtS | r;|td fv r;t|jvr:|d u r(dnd}||r3d| dnd| d7 }ngd| j d}tt|sNt	t|rXdt
|| d}n?|td fvrlt|rld| | d}n+|jtd fvrt|j|j}d|d u r|jn| d}n|jd urd| |j d}||rd	| n|7 }tt| jtr|d
dS |S )NrX   zifdef: z (z	required)(z
(default: r   z(default factory:  %z%%)r  r#  r   r   r7   rk   rs  r3   r   r5   r   rH  r%  r   _annotation_enum_val_to_namer   r  r   r  r
   r  )ru   r   r   r   _helpifdefr   	enum_namerI   rI   rJ   r$    s(   
 
 zCliSettingsSource._help_format).r   r   rp  r   rq  rr  rs  r   rt  r   ru  r   rv  r   rw  r   ro   r   rx  r   ry  r   rz  r   r{  r   r|  r   r   r   r}  r   r~  r  r  r  r  r  r  r  r  r  r  r   rC   rD   r   )r   r  rC   r  )r  r  rC   r  )r   r  r  r  rC   r  rQ  )r  r  rC   r  )r  r  r   ry   rC   r  )r  r  r   ry   rC   ry   )r  ry   r  r  r  rp   rC   ry   )r  ry   r  r  rC   ry   )r  ry   r  r  r  r  rC   ry   )r   r  r   ry   r   r6   rC   r  )r   r  r   ry   r   r6   rC   rD   )r   r  rC   r  )rC   r}   )
r  r  r  ry   r   r   rq   r   rC   r  )r  r  rC   r  )r}  r}   r~  r  r  r  r  r  r  r  r  r  r  r   rC   rD   )r  r   r   r  r
  r  r  ry   r  ry   r  r   r  r  r   r   rC   r
   )r   ry   rC   ry   )rq   r   r   r6   r   r   rC   rD   )r  ry   r  ry   r  r  r   r3  r
  r  rC   r  )r  r   r   r  r  r  r
  r  r  ry   r  ry   r  ry   r1  r  rq   r   r   ry   r   r6   r   r3  r   r   rC   rD   )r  r   r  r:  r
  r  r  ry   r  ry   r  r   rC   rD   )r=  r   rC   r3  r   )r   r  r@  r   rC   ry   )r=  r   rC   ry   )r   ry   r   r6   r   r   rC   ry   )(r`   ra   rb   rc   r
   add_argumentr  r   
add_parseradd_subparsersr   rs   r%   r   r+  r  r  r  r  r  r  r  r  r   r}  r  r  r  r  r!  r(  r&  r)  r*  r?  rC  rM  r%  r$  r{   rI   rI   rv   rJ   ro    s    /{
&

-






&
# 




E
#
	
$ro  c                   @  s$   e Zd ZdddZedd	d
ZdS )ConfigFileSourceMixinfilesr  rC   r   c                 C  sX   |d u ri S t |ttjfr|g}i }|D ]}t| }| r)|| | q|S r   )	r   ry   r  r  r   r  r  ra  
_read_file)ru   r[  r  filer[  rI   rI   rJ   _read_files  s   z!ConfigFileSourceMixin._read_filesr  r   c                 C  r   r   rI   )ru   r  rI   rI   rJ   r\    r   z ConfigFileSourceMixin._read_fileN)r[  r  rC   r   )r  r   rC   r   )r`   ra   rb   r^  r   r\  rI   rI   rI   rJ   rZ    s    
rZ  c                      <   e Zd ZdZedfd fd	d
ZdddZdddZ  ZS )JsonConfigSettingsSourcez>
    A source class that loads variables from a JSON file
    Nr   r   	json_filer  json_file_encodingr   c                   V   |t kr|n|jd| _|d ur|n|jd| _| | j| _t || j d S )Nra  rb  )	rZ   r   r   json_file_pathrb  r^  	json_datarr   rs   )ru   r   ra  rb  rv   rI   rJ   rs        
z!JsonConfigSettingsSource.__init__r[  r   rC   r   c                 C  s<   t || jd}t|W  d    S 1 sw   Y  d S Nr]  )openrb  r   load)ru   r[  ra  rI   rI   rJ   r\    s   $z#JsonConfigSettingsSource._read_filery   c                 C  r   )Nz(json_file=r   )rw   r`   rd  r   rI   rI   rJ   r     r   z!JsonConfigSettingsSource.__repr__)r   r   ra  r  rb  r   r[  r   rC   r   r   	r`   ra   rb   rc   rZ   rs   r\  r   r{   rI   rI   rv   rJ   r`    s    
r`  c                      s:   e Zd ZdZefd fddZdddZdddZ  ZS )TomlConfigSettingsSourcez>
    A source class that loads variables from a TOML file
    r   r   	toml_filer  c                   s<   |t kr|n|jd| _| | j| _t || j d S )Nrm  )rZ   r   r   toml_file_pathr^  	toml_datarr   rs   )ru   r   rm  rv   rI   rJ   rs     s   z!TomlConfigSettingsSource.__init__r[  r   rC   r   c                 C  sb   t   t|dd}tjdk rt|W  d    S t|W  d    S 1 s*w   Y  d S )Nrb)moder=   )rP   rh  rL   rM   rN   ri  rO   )ru   r[  rm  rI   rI   rJ   r\    s   
$z#TomlConfigSettingsSource._read_filery   c                 C  r   )Nz(toml_file=r   )rw   r`   rn  r   rI   rI   rJ   r     r   z!TomlConfigSettingsSource.__repr__)r   r   rm  r  rj  r   rk  rI   rI   rv   rJ   rl    s    
	rl  c                      s4   e Zd ZdZ	dd fd	d
ZedddZ  ZS )!PyprojectTomlConfigSettingsSourcezK
    A source class that loads variables from a `pyproject.toml` file.
    Nr   r   rm  r  rC   rD   c                   sj   |  ||jdd| _|jdd| _| | j| _| jD ]
}| j|i | _qtt| 	|| j d S )Npyproject_toml_depthr   pyproject_toml_table_header)toolzpydantic-settings)
_pick_pyproject_toml_filer   r   rn  toml_table_headerr^  ro  rr   rl  rs   )ru   r   rm  r   rv   rI   rJ   rs     s   
z*PyprojectTomlConfigSettingsSource.__init__provideddepthintr   c                 C  sz   | r|   S t d }d}| s;|jjd }||k r;| r"|S t|j|jkr-	 |S |jjd }|d7 }||k s|S )zPick a `pyproject.toml` file path to use.

        Args:
            provided: Explicit path provided when instantiating this class.
            depth: Number of directories up the tree to check of a pyproject.toml.

        zpyproject.tomlr   r   )resolver   cwdr  parentry   root)rx  ry  rvr  childrI   rI   rJ   rv    s    	z;PyprojectTomlConfigSettingsSource._pick_pyproject_toml_filer   )r   r   rm  r  rC   rD   )rx  r  ry  rz  rC   r   )r`   ra   rb   rc   rs   rn  rv  r{   rI   rI   rv   rJ   rr     s    rr  c                      r_  )YamlConfigSettingsSourcez>
    A source class that loads variables from a yaml file
    Nr   r   	yaml_filer  yaml_file_encodingr   c                   rc  )Nr  r  )	rZ   r   r   yaml_file_pathr  r^  	yaml_datarr   rs   )ru   r   r  r  rv   rI   rJ   rs   3  rf  z!YamlConfigSettingsSource.__init__r[  r   rC   r   c                 C  sF   t   t|| jd}t|pi W  d    S 1 sw   Y  d S rg  )rK   rh  r  rE   	safe_load)ru   r[  r  rI   rI   rJ   r\  B  s   $z#YamlConfigSettingsSource._read_filery   c                 C  r   )Nz(yaml_file=r   )rw   r`   r  r   rI   rI   rJ   r   G  r   z!YamlConfigSettingsSource.__repr__)r   r   r  r  r  r   rj  r   rk  rI   rI   rv   rJ   r  .  s    
r  c                   @  sN   e Zd ZU ded< ded< ded< dd
dZdddZdddZdddZdS )AzureKeyVaultMappingzdict[str, str | None]_loaded_secretsrS   _secret_clientr  _secret_namessecret_clientrC   rD   c                 C  s&   i | _ || _dd | j D | _d S )Nc                 S  rD  rI   rE  )r  secretrI   rI   rJ   r
  V  rG  z1AzureKeyVaultMapping.__init__.<locals>.<listcomp>)r  r  list_properties_of_secretsr  ru   r  rI   rI   rJ   rs   P  s   zAzureKeyVaultMapping.__init__r   ry   r   c                 C  sD   || j vrz| j|j| j |< W n ty   t|w | j | S r   )r  r  
get_secretr   r   KeyError)ru   r   rI   rI   rJ   __getitem__X  s   

z AzureKeyVaultMapping.__getitem__rz  c                 C  
   t | jS r   )r   r  r   rI   rI   rJ   __len__a     
zAzureKeyVaultMapping.__len__Iterator[str]c                 C  r  r   )iterr  r   rI   rI   rJ   __iter__d  r  zAzureKeyVaultMapping.__iter__N)r  rS   rC   rD   )r   ry   rC   r   )rC   rz  )rC   r  )r`   ra   rb   __annotations__rs   r  r  r  rI   rI   rI   rJ   r  K  s   
 


	r  c                      sT   e Zd ZU ded< ded< ded< 			dd fddZdddZdddZ  ZS )AzureKeyVaultSettingsSourcery   _urlrQ   _credentialrS   r  Nr   r   url
credentialr   r   r   r   r   rC   rD   c              	     s0   t   || _|| _t j|d|dd||d d S )NTz--F)r   r   r)  r   r   r   )rW   r  r  rr   rs   )ru   r   r  r  r   r   r   rv   rI   rJ   rs   m  s   	
z$AzureKeyVaultSettingsSource.__init__Mapping[str, Optional[str]]c                 C  s   t | j| jd}t|S )N)	vault_urlr  )rS   r  r  r  r  rI   rI   rJ   r+    s   z*AzureKeyVaultSettingsSource._load_env_varsc                 C  rO  )Nz(url=rl  r   )rw   r`   r  r)  r   rI   rI   rJ   r     s   z$AzureKeyVaultSettingsSource.__repr__)NNN)r   r   r  ry   r  rQ   r   r   r   r   r   r   rC   rD   )rC   r  r   )r`   ra   rb   r  rs   r+  r   r{   rI   rI   rv   rJ   r  h  s   
 
r  Fr   ry   r   c                 C  s   |r| S |   S r   r   )r   r   rI   rI   rJ   _get_env_var_key  s   r  r   r   rZ  str | None | EnvNoneTypec                 C  s   | |kr|d us
| S t | S r   )r   )r   rZ  rI   rI   rJ   _parse_env_none_str  s   r  r,  r-  rY  c                   s    fdd|   D S )Nc                   s.   i | ]\}}r|d kst | t|qS )rX   )r  r  )r  kvr   rY  rZ  rI   rJ   r    s    z"parse_env_vars.<locals>.<dictcomp>)r   )r,  r   rY  rZ  rI   r  rJ   r.    s   r.  rW  r[  r   rX  c                C  s    t dt tj| ||||dS )Nzmread_env_file will be removed in the next version, use DotEnvSettingsSource._static_read_env_file if you mustrW  )r  r  DeprecationWarningrR  r_  )r[  rX  r   rY  rZ  rI   rI   rJ   read_env_file  s   r  r   r  r   	list[Any]c                 C  s   z| d urt | tr| jdd }|d ur|dkr|} W n	 ty%   Y nw tdd |D r1dS t| trAt| ^}}t	||S t
| }|tu rKdS t| p\t|p\t|dp\t|dS )Nr~  RootModelRootTypec                 s  r5  r   )r   r*   )r  mdrI   rI   rJ   rA    rB  z)_annotation_is_complex.<locals>.<genexpr>F__pydantic_core_schema____get_pydantic_core_schema__)r   r+   r  r   	TypeErrorrC  r   r9   r:   r   r;   r,   _annotation_is_complex_innerr   )r   r   root_annotationinnermetaoriginrI   rI   rJ   r     s0   

r   c              	   C  s2   t | ttfr	dS t | ttttttt	fpt
| S r  )r4   ry   bytesr)   r   r!   r  r"  	frozensetr   r   r   rI   rI   rJ   r    s
   r  c                   s   t  fddt| D S )Nc                 3  s    | ]}t | V  qd S r   )r   r  r   rI   rJ   rA    rB  z$_union_is_complex.<locals>.<genexpr>)rC  r:   )r   r   rI   r  rJ   r     s   r   typestuple[Any, ...]r  r  c                 C  sP   |rt | } |du rt| |v rdS t| D ]}t||d|dr# dS q| |v S )NT)r  r  )r  r;   r:   r  )r   r  r  r  r<  rI   rI   rJ   r    s   r  r   c                 C  s(   t | tkrt| d } t | tks| S r  )r;   r8   r:   r  rI   rI   rJ   r    s   r  Optional[str]c                 C  sN   | t | gt| R D ]}t|tr$|tdd |D v r$||j  S qd S )Nc                 s      | ]}|j V  qd S r   )r   rF  rI   rI   rJ   rA        z/_annotation_enum_val_to_name.<locals>.<genexpr>)r;   r:   r4   r   r  r   )r   r   r<  rI   rI   rJ   rS    s   
rS  r   c                 C  sL   | t | gt| R D ]}t|tr#|tdd |D v r#||   S qd S )Nc                 s  r  r   rE  rF  rI   rI   rJ   rA  	  r  z/_annotation_enum_name_to_val.<locals>.<genexpr>)r;   r:   r4   r   r  )r   r   r<  rI   rI   rJ   r2  	  s   
r2  r   	type[Any]dict[str, FieldInfo]c                 C  s8   t | rt| dr| jS t| r| jS td| j d)N__pydantic_fields__zError: z? is not subclass of BaseModel or pydantic.dataclasses.dataclass)r5   r   r  r3   r   rg   r`   )r   rI   rI   rJ   r   
	  s
   r   r   r   r6   r  r:  tuple[tuple[str, ...], bool]c           
      C  s"  g }d}t |j|jfs|| g7 }d}nkg }|j|jfD ]7}|d u r#qt|tr0|| d}qt|trN|jD ]}t|trG|| d}q8|| q8q|| q|D ](}	tt|	j	d }|sf|
 n|}t|	j	dkrqdnd||< |s~|r~|| qV|sdd |D }tt||fS )	NTFr   r   r   r   c                 S  s   g | ]}|  qS rI   r  )r  
alias_namerI   rI   rJ   r
  2	  s    z$_get_alias_names.<locals>.<listcomp>)rC  r   r   r   ry   r   r'   choicesr$   r  r   r   r  r   fromkeys)
r   r   r  r   r   r,  new_alias_pathsr   r   
alias_pathrI   rI   rJ   r   	  s<   







r   r=  c                 C  s   t | ttfS r   )r   r   r   )r=  rI   rI   rJ   rH  6	  s   rH  )rC   rD   )TN)r   rA   r   rp   ro   r   rC   r   )F)r   ry   r   rp   rC   ry   r   )r   r   rZ  r   rC   r  )FFN)
r,  r-  r   rp   rY  rp   rZ  r   rC   r-  rm  )r   r  r   r  rC   rp   )r   r  rC   rp   )TF)
r   r  r  r  r  rp   r  rp   rC   rp   )r   r   rC   r   )r   r  r   r   rC   r  )r   r  r   r   rC   r   )r   r  rC   r  )
r   ry   r   r6   r  r:  r   rp   rC   r  )r=  r   rC   rp   )
__future__r   _annotationsr   r  r  r  rL   rO  r  abcr   r   rM   argparser   r	   r
   r   r   r   collectionsr   r   dataclassesr   r   enumr   pathlibr   textwrapr   r  r   r   r   r   r   r   r   r   r   r   r   r    r!   r"   r#   r$   r%   rJ  dotenvr&   pydanticr'   r(   r)   r*   r+   r,   r-   pydantic._internal._reprr.    pydantic._internal._typing_extrar/   r0   r1   pydantic._internal._utilsr2   r3   r4   pydantic.dataclassesr5   pydantic.fieldsr6   pydantic_corer7   r8   r9   r:   r;   pydantic_settings.utilsr<   rO   rN   rE   pydantic._internal._dataclassesr?   pydantic_settings.mainr@   rA   rK   rP   rW   ry   r[   rY   rZ   r  r\   r^   re   r  rg   rj   rk   rl   rm   rn   r|   r}   CliSubCommandCliPositionalArgrp   r~   r  r  r#  CliSuppressr   r   r   r   r   r   r  r(  rR  ro  rZ  r`  rl  rr  r  r  r  r  r  r.  r  r   r  r   r  r  rS  r2  r   r   rH  rI   rI   rI   rJ   <module>   s    
@$





1m(" <k ht       !.#

"
	



	$