o
    i"                     @  sL   d dl mZ d dlmZ ddd	Z	
	
	ddddZ				
ddddZdS )    )annotations)defaultdictschemadictparamstrreturnc                 C  s`   |  di }||d}|du r| S || d< ||  dg v r.| d | | d s.| d | S )zwReturn a new schema with *param* removed from `properties`, `required`,
    and (if no longer referenced) `$defs`.
    
propertiesNrequired)getpopremove)r   r   propsremoved r   c/var/www/html/karishye-ai-python/venv/lib/python3.10/site-packages/fastmcp/utilities/json_schema.py_prune_param   s   
r   FTprune_titlesboolprune_additional_properties
prune_defsc                   s   sss| S t  tt | d}			dd fdd| dd ra|ra| D ]
\}}||d q2dd fddt| D ]}|sX|| qM|sa| dd | S )aK  
    Optimize JSON schemas in a single traversal for better performance.

    This function combines three schema cleanup operations that would normally require
    separate tree traversals:

    1. **Remove unused definitions** (prune_defs): Finds and removes `$defs` entries
       that aren't referenced anywhere in the schema, reducing schema size.

    2. **Remove titles** (prune_titles): Strips `title` fields throughout the schema
       to reduce verbosity while preserving functional information.

    3. **Remove restrictive additionalProperties** (prune_additional_properties):
       Removes `"additionalProperties": false` constraints to make schemas more flexible.

    **Performance Benefits:**
    - Single tree traversal instead of multiple passes (2-3x faster)
    - Immutable design prevents shared reference bugs
    - Early termination prevents runaway recursion on deeply nested schemas

    **Algorithm Overview:**
    1. Traverse main schema, collecting $ref references and applying cleanups
    2. Traverse $defs section to map inter-definition dependencies
    3. Remove unused definitions based on reference analysis

    Args:
        schema: JSON schema dict to optimize (not modified)
        prune_titles: Remove title fields for cleaner output
        prune_additional_properties: Remove "additionalProperties": false constraints
        prune_defs: Remove unused $defs entries to reduce size

    Returns:
        A new optimized schema dict

    Example:
        >>> schema = {
        ...     "type": "object",
        ...     "title": "MySchema",
        ...     "additionalProperties": False,
        ...     "$defs": {"UnusedDef": {"type": "string"}}
        ... }
        >>> result = _single_pass_optimize(schema, prune_titles=True, prune_defs=True)
        >>> # Result: {"type": "object", "additionalProperties": False}
    $defsNFr   nodeobjectcurrent_def_name
str | Noneskip_defs_sectionr   depthintr   Nonec           	        s@  |dkrdS t  trr2 d}t |tr2|dr2|dd }|r-| | n| rHd v rHt fdd	d
D rH 	d rV ddu rV 	d  
 D ],\}}|re|dkreqZ|dv r}t |tr}|D ]}|||d d qpqZ|||d d qZdS t  tr D ]}|||d d qdS dS )zATraverse schema tree, collecting $ref info and applying cleanups.2   N$refz#/$defs//titlec                 3  s    | ]}| v V  qd S Nr   ).0kr   r   r   	<genexpr>u   s
    
zD_single_pass_optimize.<locals>.traverse_and_clean.<locals>.<genexpr>)typer	   r!   itemsallOfoneOfanyOfr
   additionalPropertiesFr   )r,   r-   r.      )r   )
isinstancer   r   r   
startswithsplitappendaddanyr   r+   list)	r   r   r   r   refreferenced_defkeyvalueitem)def_dependenciesr   r   r   	root_refstraverse_and_cleanr(   r   r?   X   sB   





z1_single_pass_optimize.<locals>.traverse_and_cleanT)r   )r   def_namer   visitingset[str] | Nonec                   sf   | v rdS   | g }|r1|du rt }| |v rdS || hB }|D ]}||vr0||r0 dS q"dS )z<Check if a definition is used, handling circular references.TNF)r   set)r@   rA   referencing_defsreferencing_def)r=   is_def_usedr>   r   r   rF      s    

z*_single_pass_optimize.<locals>.is_def_used)NFr   )
r   r   r   r   r   r   r   r   r   r   r%   )r@   r   rA   rB   r   r   )rC   r   r7   r   r+   keysr   )r   r   r   r   defsr@   
def_schemar   )r=   rF   r   r   r   r>   r?   r   _single_pass_optimize   s.   2
C
rJ   Nprune_paramslist[str] | Nonec                 C  s:   |pg D ]}t | |d} q|s|s|rt| |||d} | S )a  
    Remove the given parameters from the schema.

    Args:
        schema: The schema to compress
        prune_params: List of parameter names to remove from properties
        prune_defs: Whether to remove unused definitions
        prune_additional_properties: Whether to remove additionalProperties: false
        prune_titles: Whether to remove title fields from the schema
    )r   )r   r   r   )r   rJ   )r   rK   r   r   r   r   r   r   r   compress_schema   s   rM   )r   r   r   r   r   r   )FFT)
r   r   r   r   r   r   r   r   r   r   )NTTF)r   r   rK   rL   r   r   r   r   r   r   r   r   )
__future__r   collectionsr   r   rJ   rM   r   r   r   r   <module>   s    
 0