
    i9<                        d 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	Z	ddl
mZ ddlmZ  ej                  e      Zg dZ G d	 d
      ZdefdZdefdZdedededefdZdeez  ddfdZdefdZdeeef   fdZy)a  
ProjectX Configuration Management

Author: @TexasCoding
Date: 2025-08-02

Overview:
    Handles configuration for the ProjectX client, including environment variables,
    config files, and default settings. Provides comprehensive configuration management
    with priority-based loading, validation, and customization for different deployment
    environments.

Key Features:
    - Priority-based configuration loading (Environment > Config file > Defaults)
    - Environment variable support with automatic type conversion
    - Configuration file management with JSON format
    - Configuration validation and error handling
    - Custom configuration creation for different endpoints
    - Authentication configuration management
    - Environment setup validation and status checking

Configuration Sources:
    - Environment variables with PROJECTX_ prefix
    - JSON configuration files with customizable paths
    - Default configuration with TopStepX endpoints
    - Custom configuration for different ProjectX deployments

Example Usage:
    ```python
    from project_x_py.config import (
        load_default_config,
        create_custom_config,
        ConfigManager,
        check_environment,
    )

    # Load default configuration
    config = load_default_config()

    # Create custom configuration
    custom_config = create_custom_config(
        user_hub_url="https://custom.projectx.com/hubs/user",
        market_hub_url="https://custom.projectx.com/hubs/market",
    )

    # Use configuration manager
    manager = ConfigManager("config.json")
    config = manager.load_config()

    # Check environment setup
    status = check_environment()
    if status["auth_configured"]:
        print("Authentication configured")
    else:
        print(f"Missing: {status['missing_required']}")
    ```

Configuration Priority:
    1. Environment variables (highest priority)
    2. Configuration file (JSON format)
    3. Default values (lowest priority)

Environment Variables:
    - PROJECTX_API_URL: Base API URL
    - PROJECTX_REALTIME_URL: WebSocket URL
    - PROJECTX_USER_HUB_URL: User hub URL
    - PROJECTX_MARKET_HUB_URL: Market hub URL
    - PROJECTX_TIMEZONE: Timezone for timestamps
    - PROJECTX_TIMEOUT_SECONDS: Request timeout
    - PROJECTX_RETRY_ATTEMPTS: Retry attempts
    - PROJECTX_RETRY_DELAY_SECONDS: Retry delay
    - PROJECTX_REQUESTS_PER_MINUTE: Rate limiting
    - PROJECTX_BURST_LIMIT: Burst limit

Authentication Variables:
    - PROJECT_X_API_KEY: API key for authentication
    - PROJECT_X_USERNAME: Username for authentication

Configuration Validation:
    - URL format validation for all endpoints
    - Numeric value validation for timeouts and limits
    - Timezone validation using pytz
    - Authentication credential validation
    - Comprehensive error reporting

See Also:
    - `models.ProjectXConfig`: Configuration data model
    - `utils.environment`: Environment variable utilities
    N)asdict)Path)Any)ProjectXConfig)get_env_var)ConfigManagercheck_environmentcreate_config_templatecreate_custom_configget_default_config_pathload_default_configload_topstepx_configc                       e Zd ZdZddeez  dz  fdZdefdZde	ee
f   fdZde	ee
f   fdZ	 dd	ed
eez  dz  ddfdZde	eef   fdZd	edefdZy)r   z
    Configuration manager for ProjectX client.

    Handles loading configuration from:
    1. Environment variables
    2. Configuration files
    3. Default values

    Priority order: Environment variables > Config file > Defaults
    Nconfig_filec                 :    |rt        |      nd| _        d| _        y)z
        Initialize configuration manager.

        Args:
            config_file: Optional path to configuration file
        N)r   r   _config)selfr   s     L/home/work/apex_v16/venv/lib/python3.12/site-packages/project_x_py/config.py__init__zConfigManager.__init__   s     >I[(9d.2    returnc                    | j                   | j                   S t        t                     }| j                  r^| j                  j	                         rD	 | j                         }|j                  |       t        j                  d| j                          | j                         }|j                  |       t        di || _         | j                   S # t        $ r/}t        j                  d| j                   d|        Y d}~pd}~ww xY w)zo
        Load configuration with priority order.

        Returns:
            ProjectXConfig instance
        NzLoaded configuration from zFailed to load config file :  )r   r   r   r   exists_load_config_fileupdateloggerinfo	Exceptionwarning_load_env_config)r   config_dictfile_confige
env_configs        r   load_configzConfigManager.load_config   s     <<#<< ^-.  0 0 7 7 9V"446"";/89I9I8JKL
 **,
:&%44||  V!<T=M=M<NbQRPSTUUVs   AC 	D%DDc                    | j                   r| j                   j                         si S 	 t        | j                   d      5 }|j                         }t	        j
                  |      }t        |t              rt        |      ni cddd       S # 1 sw Y   yxY w# t        j                  t        f$ r$}t        j                  d|        i cY d}~S d}~ww xY w)z"Load configuration from JSON file.zutf-8)encodingNzError loading config file: )r   r   openreadorjsonloads
isinstancedictJSONDecodeErrorOSErrorr   error)r   fcontentdatar%   s        r   r   zConfigManager._load_config_file   s    t'7'7'>'>'@I	d&&9 DQ&&(||G,%/d%;tDzD D D &&0 	LL6qc:;I	s<   B AB	B BB B C2CCCc                    i }ddddddt         fdt         fdt        fd	t         fd
t         fd
}|j                         D ]N  \  }}t        j                  j                  |      }|(t        |t              r|\  }}	  ||      ||<   J|||<   P |S # t        $ r)}t        j                  d| d| d| d       Y d}~d}~ww xY w)z.Load configuration from environment variables.api_urlrealtime_urluser_hub_urlmarket_hub_urltimezonetimeout_secondsretry_attemptsretry_delay_secondsrequests_per_minuteburst_limit
PROJECTX_API_URLPROJECTX_REALTIME_URLPROJECTX_USER_HUB_URLPROJECTX_MARKET_HUB_URLPROJECTX_TIMEZONEPROJECTX_TIMEOUT_SECONDSPROJECTX_RETRY_ATTEMPTSPROJECTX_RETRY_DELAY_SECONDSPROJECTX_REQUESTS_PER_MINUTEPROJECTX_BURST_LIMITNzInvalid value for r   z ())intfloatitemsosenvirongetr.   tuple
ValueErrorr   r!   )	r   r&   env_mappingsenv_var
config_keyvaluekey
value_typer%   s	            r   r"   zConfigManager._load_env_config   s    
 !*%3%3'7!+):C(@(8#'>-BE,J-BC,H%2C$8
 $0#5#5#7 
	3GZJJNN7+E j%0&0OCV*4U*;
3 .3Jz*
	3  & V);G9BugRPQsRS'TUUVs   <B	CB>>Cconfig	file_pathc                    |rt        |      n| j                  }|t        d      	 |j                  j	                  dd       t        |      }t        |d      5 }|j                  t        j                  |t        j                               ddd       t        j                  d|        y# 1 sw Y   "xY w# t        $ r!}t        j                  d| d	|         d}~ww xY w)
z
        Save configuration to file.

        Args:
            config: Configuration to save
            file_path: Optional path to save to (uses self.config_file if None)
        NzNo config file path specifiedTparentsexist_okwboptionzConfiguration saved to zFailed to save config to r   )r   r   rT   parentmkdirr   r*   writer,   dumpsOPT_INDENT_2r   r   r    r2   )r   r[   r\   target_filer#   r3   r%   s          r   save_configzConfigManager.save_config   s     *3d9o8H8H<==	$$TD$A !.Kk4( OA[9L9LMNO KK1+?@O O
  	LL4[MA3GH	s/   4B> 5B2 B> 2B;7B> >	C(C##C(c                     t        dd      }t        dd      }|st        d      |st        d      t        |t              rt	        |      dk  rt        d      ||d	S )
z
        Get authentication configuration from environment variables.

        Returns:
            Dictionary with authentication settings

        Raises:
            ValueError: If required authentication variables are missing or invalid
        PROJECT_X_API_KEYT)requiredPROJECT_X_USERNAMEz2PROJECT_X_API_KEY environment variable is requiredz3PROJECT_X_USERNAME environment variable is required
   zMInvalid PROJECT_X_API_KEY format - must be a string longer than 10 characters)api_keyusername)r   rT   r.   strlen)r   rp   rq   s      r   get_auth_configzConfigManager.get_auth_config   sn     1DA3dCQRRRSS'3'3w<"+<_  #99r   c                    g }g d}|D ][  }t        ||      }|rt        |t              s|j                  | d       6|j	                  d      rH|j                  | d       ] |j
                  dk  r|j                  d       |j                  dk  r|j                  d       |j                  dk  r|j                  d       |j                  dk  r|j                  d	       |j                  dk  r|j                  d
       	 ddl
}|j                  |j                         |rt        ddj                  |             y# t        $ r! |j                  d|j                          Y Iw xY w)z
        Validate configuration settings.

        Args:
            config: Configuration to validate

        Returns:
            True if configuration is valid

        Raises:
            ValueError: If configuration is invalid
        )r7   r8   r9   r:   z must be a non-empty string)zhttp://zhttps://zwss://z must be a valid URLr   z timeout_seconds must be positivez#retry_attempts must be non-negativez(retry_delay_seconds must be non-negativez$requests_per_minute must be positivezburst_limit must be positiveNzInvalid timezone: z!Configuration validation failed: z; T)getattrr.   rr   append
startswithr<   r=   r>   r?   r@   pytzr;   r    rT   join)r   r[   errorsrequired_urls	url_fieldurlry   s          r   validate_configzConfigManager.validate_config  sc    $
 ' 	BI&),Cjc2+FGH^^$EF+?@A	B !!Q&MM<=  1$MM?@%%)MMDE%%*MM@A"MM89	BMM&//* @6AR@STUU  	BMM.v.?@A	Bs   E 'E10E1)N)__name__
__module____qualname____doc__rr   r   r   r   r'   r/   r   r   r"   rj   rt   boolr   r   r   r   r   r   s   s    	3C$J$5 3^ :4S> $sCx. F (, :$ 
	@:c3h :24n 4 4r   r   r   c                  6    t               } | j                         S )zw
    Load default configuration with environment variable overrides.

    Returns:
        ProjectXConfig instance
    )r   r'   )managers    r   r   r   D  s     oG  r   c                      t               S )z
    Load configuration for TopStepX endpoints (uses default config).

    Returns:
        ProjectXConfig: Configuration with TopStepX URLs
    )r   r   r   r   r   r   O  s       r   r9   r:   kwargsc                     t               }| |_        ||_        |j                         D ]  \  }}t	        ||      st        |||       ! |S )a  
    Create custom configuration with specified URLs.

    Args:
        user_hub_url: Custom user hub URL
        market_hub_url: Custom market hub URL
        **kwargs: Additional configuration parameters

    Returns:
        ProjectXConfig: Custom configuration instance
    )r   r9   r:   rO   hasattrsetattr)r9   r:   r   r[   rY   rX   s         r   r   r   Y  sT     !"F&F*F lln (
U63FC'( Mr   r\   c                 |   t               }t        |      }ddddddddd	d
dd
d|}t        |       } | j                  j	                  dd       t        | d      5 }|j                  t        j                  |t        j                               ddd       t        j                  d|         y# 1 sw Y   "xY w)zo
    Create a configuration file template.

    Args:
        file_path: Path where to create the template
    zProjectX Configuration TemplatezBase URL for the ProjectX APIz WebSocket URL for real-time datazSignalR hub URL for user eventszSignalR hub URL for market datazTimezone for timestamp handlingzRequest timeout in secondsz,Number of retry attempts for failed requestszDelay between retry attemptsz#Rate limiting - requests per minutezRate limiting - burst limit)
r7   r8   r9   r:   r;   r<   r=   r>   r?   r@   )_comment_descriptionTr^   ra   rb   Nz"Configuration template created at )r   r   r   rd   re   r*   rf   r,   rg   rh   r   r   )r\   template_configr#   templater3   s        r   r
   r
   s  s     %&O"("9K 66>=?9;L#A#H8
 H" YI4$7	i	 D!	Xf.A.ABCD KK4YK@AD Ds   5B22B;c                      t        j                         dz  dz  dz  t        j                         dz  t        j                         dz  g} | D ]  }|j                         s|c S  | d   S )zd
    Get the default configuration file path.

    Returns:
        Path to default config file
    z.configprojectxzconfig.jsonzprojectx_config.jsonz.projectx_config.jsonr   )r   homecwdr   )possible_pathspaths     r   r   r     sm     			i*,}<
++
,,N  ;;=K !r   c                     ddg g d} 	 t        d      }t        d      }|r|rd| d<   n,|s| d   j                  d       |s| d   j                  d       t	               }|j                         rd| d<   t        |      | d	<   g d
}|D ]6  }t        j                  j                  |      s#| d   j                  |       8 | S # t        $ r | d   j                  ddg       Y w xY w)zh
    Check environment setup for ProjectX.

    Returns:
        Dictionary with environment status
    F)auth_configuredconfig_file_existsenvironment_overridesmissing_requiredrl   rn   Tr   r   r   config_file_pathrA   r   )
r   rw   r    extendr   r   rr   rP   rQ   rR   )statusrp   rq   default_pathenv_varsvars         r   r	   r	     s    !#!#	FW1234x(,F$%)*112EF)*112FG
 12L'+#$%(%6!"H  8::>>#*+22378 M7  W!"))+>@T*UVWs   AC C%$C%)r   loggingrP   dataclassesr   pathlibr   typingr   r,   project_x_py.modelsr   project_x_py.utilsr   	getLoggerr   r   __all__r   r   r   rr   r   r
   r   r/   r	   r   r   r   <module>r      s   Xt  	     . *			8	$N Nb!^ !!n !'*694"BcDj "BT "BJ .54S> 5r   