o
    ưiJ                     @   s  d dl Z d dlmZmZ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 d dlmZmZ d dlmZmZmZmZmZmZ e Ze Zd	ed
edefddZdd ZejddgeegedeefdefddZej ddgeegedeefdedefddZ!dZ"de#fddZ$de#fddZ%de#fdd Z&ej'd!dgeegedeefdedefd"d#Z(ej'd$dgeegedeefdedefd%d&Z)ej'd'dgeegedeefdedefd(d)Z*ej+d*dgeegedeefdefd+d,Z,dS )-    N)	APIRouterDependsHTTPException)verbose_proxy_logger)SensitiveDataMasker)CommonProxyErrorsLitellmUserRolesUserAPIKeyAuth)user_api_key_auth)decrypt_value_helperencrypt_value_helper)CloudZeroExportRequestCloudZeroExportResponseCloudZeroInitRequestCloudZeroInitResponseCloudZeroSettingsUpdateCloudZeroSettingsViewapi_keyconnection_idtimezonec                    sz   ddl m} |du rtddtjjidt| }|||d}|jjj	dd	id	t
|d
dt
|iddI dH  dS )z
    Store CloudZero settings in the database with encrypted API key.

    Args:
        api_key: CloudZero API key to encrypt and store
        connection_id: CloudZero connection ID
        timezone: Timezone for date handling
    r   prisma_clientN  errorstatus_codedetailr   r   r   
param_namecloudzero_settings)r   param_valuer    )createupdate)wheredata)litellm.proxy.proxy_serverr   r   r   db_not_connected_errorvaluer   dblitellm_configZupsertjsondumps)r   r   r   r   encrypted_api_keyr    r-   g/home/app/Keep/.python/lib/python3.10/site-packages/litellm/proxy/spend_tracking/cloudzero_endpoints.py_set_cloudzero_settings   s(   	
r/   c                     s   ddl m}  | du rtddtjjid| jjjddid	I dH }|du s+|j	du r-i S t
|j	tr7|j	}nt
|j	trDt|j	}nt|j	}|d
}|rgt|ddd}|du rctdddid||d
< |S )z
    Retrieve CloudZero settings from the database with decrypted API key.

    Returns:
        dict: CloudZero settings with decrypted API key, or empty dict if not configured
    r   r   Nr   r   r   r   r   r#   r   Zcloudzero_api_key)keyZexception_typezGFailed to decrypt CloudZero API key. Check your salt key configuration.)r%   r   r   r   r&   r'   r(   r)   
find_firstr    
isinstancedictstrr*   loadsgetr   )r   cloudzero_configsettingsr,   Zdecrypted_api_keyr-   r-   r.   _get_cloudzero_settingsC   s<   


r:   z/cloudzero/settingsZ	CloudZero)tagsdependenciesZresponse_modeluser_api_key_dictc              
      s   | j tjkrtddtjjidz(t I dH }|s#tdddddW S t	
|}t|d|d|dd	dW S  tyG } z|d}~w tyi } ztd
t|  tdddt| idd}~ww )ad  
    View current CloudZero settings.

    Returns the current CloudZero configuration with the API key masked for security.
    Only the first 4 and last 4 characters of the API key are shown.
    Returns null/empty values when settings are not configured (consistent with other settings endpoints).

    Only admin users can view CloudZero settings.
      r   r   N)Zapi_key_maskedr   r   statusr   r   r   Z
configuredz%Error retrieving CloudZero settings: r   z'Failed to retrieve CloudZero settings: )	user_roler   PROXY_ADMINr   r   not_allowed_accessr'   r:   r   _sensitive_maskerZ	mask_dictr7   	Exceptionr   r   r5   )r=   r9   Zmasked_settingser-   r-   r.   get_cloudzero_settingsr   sB   

rF   requestc              
      sB  |j tjkrtddtjjidt| j| j	| j
gs#tdddidz@t I dH }| jdur2| jn|d }| j	dur>| j	n|d }| j
durJ| j
n|d	 }t|||d
I dH  td tdddW S  ty~ } z|jdkrxtdddid|d}~w ty } ztdt|  tdddt| idd}~ww )a  
    Update existing CloudZero settings.

    Allows updating individual CloudZero configuration fields without requiring all fields.
    Only provided fields will be updated; others will remain unchanged.

    Parameters:
    - api_key: (Optional) New CloudZero API key for authentication
    - connection_id: (Optional) New CloudZero connection ID for data submission
    - timezone: (Optional) New timezone for date handling

    Only admin users can update CloudZero settings.
    r>   r   r   i  z.At least one field must be provided for updateNr   r   r   r   z'CloudZero settings updated successfullysuccessmessager?     zTCloudZero settings not found. Please initialize settings first using /cloudzero/initz#Error updating CloudZero settings: r   z%Failed to update CloudZero settings: )r@   r   rA   r   r   rB   r'   anyr   r   r   r:   r/   r   infor   r   rD   r   r5   )rG   r=   Zcurrent_settingsZupdated_api_keyZupdated_connection_idZupdated_timezonerE   r-   r-   r.   update_cloudzero_settings   sf   





rN   Freturnc               
      s   z$ddl m}  | du rW dS | jjjddidI dH }|duo$|jduW S  tyB } ztdt	|  W Y d}~dS d}~ww )	a  
    Check if CloudZero is setup in the database.

    CloudZero is considered setup in the database if:
    - CloudZero settings exist in the database
    - The settings have a non-None value

    Returns:
        bool: True if CloudZero is active, False otherwise
    r   r   NFr   r   r0   z!Error checking CloudZero status: )
r%   r   r(   r)   r2   r    rD   r   r   r5   )r   r8   rE   r-   r-   r.   is_cloudzero_setup_in_db
  s   rP   c                  C   s   ddl } d| jv S )a	  
    Check if CloudZero is setup in config.yaml or environment variables.

    CloudZero is considered setup in config if:
    - "cloudzero" is in the callbacks list in config.yaml, OR
    Returns:
        bool: True if CloudZero is configured, False otherwise
    r   NZ	cloudzero)litellm	callbacks)rQ   r-   r-   r.   is_cloudzero_setup_in_config(  s   	
rS   c               
      sb   zt  rW dS t I dH rW dS W dS  ty0 }  ztdt|   W Y d} ~ dS d} ~ ww )al  
    Check if CloudZero is setup in either config.yaml/env vars OR database.

    CloudZero is considered setup if:
    - CloudZero is configured in config.yaml callbacks, OR
    - CloudZero environment variables are set, OR  
    - CloudZero settings exist in the database

    Returns:
        bool: True if CloudZero is configured anywhere, False otherwise
    TNFz Error checking CloudZero setup: )rS   rP   rD   r   r   r5   )rE   r-   r-   r.   is_cloudzero_setup5  s   rT   z/cloudzero/initc              
      s   |j tjkrtddtjjidzt| j| j	| j
dI dH  td tdddW S  tyM } ztd	t|  td
ddt| idd}~ww )a  
    Initialize CloudZero settings and store in the database.

    This endpoint stores the CloudZero API key, connection ID, and timezone configuration
    in the proxy database for use by the CloudZero logger.

    Parameters:
    - api_key: CloudZero API key for authentication
    - connection_id: CloudZero connection ID for data submission
    - timezone: Timezone for date handling (default: UTC)

    Only admin users can configure CloudZero settings.
    r>   r   r   r   Nz+CloudZero settings initialized successfullyrH   rI   z'Error initializing CloudZero settings: r   z)Failed to initialize CloudZero settings: )r@   r   rA   r   r   rB   r'   r/   r   r   r   r   rM   r   rD   r   r5   )rG   r=   rE   r-   r-   r.   init_cloudzero_settingsQ  s0   

rU   z/cloudzero/dry-runc              
      s   |j tjkrtddtjjidz+ddlm} | }|j	| j
dI dH }td td	d
||r8|ddW S ddW S  ty_ } ztdt|  tdddt| idd}~ww )aO  
    Perform a dry run export using the CloudZero logger.

    This endpoint uses the CloudZero logger to perform a dry run export,
    which returns the data that would be exported without actually sending it to CloudZero.

    Parameters:
    - limit: Optional limit on number of records to process (default: 10000)

    Returns:
    - usage_data: Sample of the raw usage data (first 50 records)
    - cbf_data: CloudZero CBF formatted data ready for export
    - summary: Statistics including total cost, tokens, and record counts

    Only admin users can perform CloudZero exports.
    r>   r   r   r   CloudZeroLogger)limitNz/CloudZero dry run export completed successfullyz0CloudZero dry run export completed successfully.rH   summaryrJ   r?   Zdry_run_datarY   z+Error performing CloudZero dry run export: r   z,Failed to perform CloudZero dry run export: )r@   r   rA   r   r   rB   r'   (litellm.integrations.cloudzero.cloudzerorW   Zdry_run_export_usage_datarX   r   rM   r   r7   rD   r   r5   )rG   r=   rW   loggerZdry_run_resultrE   r-   r-   r.   cloudzero_dry_run_export  s>   

r]   z/cloudzero/exportc              
      s   |j tjkrtddtjjidz:t I dH }ddlm	} ||
d|
d|
d	d
}|j| j| j| j| jdI dH  td tdddddW S  tyn } ztdt|  tdddt| idd}~ww )a|  
    Perform an actual export using the CloudZero logger.

    This endpoint uses the CloudZero logger to export usage data to CloudZero AnyCost API.

    Parameters:
    - limit: Optional limit on number of records to export
    - operation: CloudZero operation type ("replace_hourly" or "sum", default: "replace_hourly")

    Only admin users can perform CloudZero exports.
    r>   r   r   Nr   rV   r   r   r   r   )rX   	operationstart_time_utcend_time_utcz'CloudZero export completed successfullyrH   rZ   z#Error performing CloudZero export: r   z$Failed to perform CloudZero export: )r@   r   rA   r   r   rB   r'   r:   r[   rW   r7   Zexport_usage_datarX   r^   r_   r`   r   rM   r   rD   r   r5   )rG   r=   r9   rW   r\   rE   r-   r-   r.   cloudzero_export  sF   

ra   z/cloudzero/deletec              
      s  | j tjkrtddtjjidzFddlm} |du r&tddtj	jid|j
jjdd	id
I dH }|du r?tdddid|j
jjdd	id
I dH  td tdddW S  tye } z|d}~w ty } ztdt|  tdddt| idd}~ww )a[  
    Delete CloudZero settings from the database.

    This endpoint removes the CloudZero configuration (API key, connection ID, timezone)
    from the proxy database. Only the CloudZero settings entry will be deleted;
    other configuration values in the database will remain unchanged.

    Only admin users can delete CloudZero settings.
    r>   r   r   r   r   Nr   r   r   r0   rK   zCloudZero settings not foundz'CloudZero settings deleted successfullyrH   rI   z#Error deleting CloudZero settings: z%Failed to delete CloudZero settings: )r@   r   rA   r   r   rB   r'   r%   r   r&   r(   r)   r2   deleter   rM   r   rD   r   r5   )r=   r   r8   rE   r-   r-   r.   delete_cloudzero_settings  sN   


rc   )-r*   Zfastapir   r   r   Zlitellm._loggingr   Z0litellm.litellm_core_utils.sensitive_data_maskerr   Zlitellm.proxy._typesr   r   r	   Z$litellm.proxy.auth.user_api_key_authr
   Z0litellm.proxy.common_utils.encrypt_decrypt_utilsr   r   Z'litellm.types.proxy.cloudzero_endpointsr   r   r   r   r   r   ZrouterrC   r5   r/   r:   r7   rF   putrN   Z%_cloudzero_background_job_initializedboolrP   rS   rT   postrU   r]   ra   rb   rc   r-   r-   r-   r.   <module>   s     	&/5T.8<