
    "<i"                    H    d dl mZ d dlmZ ddZ	 	 	 dddZ	 	 	 	 dddZdS )    )annotations)defaultdictschemadictparamstrreturnc                   |                      di           }|                    |d          }|| S || d<   ||                      dg           v r8| 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removeds       /Users/kimhansen/Desktop/03 Workspace/ceo-agents/chl-effectiveness/mcp-servers/whoop/.venv/lib/python3.11/site-packages/fastmcp/utilities/json_schema.py_prune_paramr      s     JJ|R((Eiit$$G !F<

:r****z!!%(((j! 	#JJz"""M    FTprune_titlesboolprune_additional_properties
prune_defsc                  	
 sss| S t                      	t          t                    |                     d          }	 	 	 dd	
fd
 
| d           r|r|                                D ]\  }} 
||           dd	fdt          |                                          D ]"} |          s|                    |           #|s|                     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                R    |dk    rdS t           t                    rYr                     d          }t          |t                    rc|                    d          rN|                    d          d         }|r	|                             |           n                    |           r4d v r0t           fdd	D                       r 	                    d           
r,                     d
          du r 	                    d
            
                                D ]O\  }}|r|dk    r|dv r,t          |t                    r|D ]} |||dz              > |||dz              PdS t           t                    r D ]} |||dz              dS dS )zATraverse schema tree, collecting $ref info and applying cleanups.2   N$refz#/$defs//titlec              3      K   | ]}|v V  	d S N ).0kr   s     r   	<genexpr>zD_single_pass_optimize.<locals>.traverse_and_clean.<locals>.<genexpr>u   s;         I     r   )typer   r%   itemsallOfoneOfanyOfr   additionalPropertiesFr   )r1   r2   r3      )r    )
isinstancer   r   r   
startswithsplitappendaddanyr   r0   list)r   r   r   r    refreferenced_defkeyvalueitemdef_dependenciesr   r   r   	root_refstraverse_and_cleans   `        r   rD   z1_single_pass_optimize.<locals>.traverse_and_cleanX   sZ    2::FdD!! 6	L 	6hhv&&c3'' 6CNN:,F,F 6%(YYs^^B%7N' 6(8??@PQQQQ "n555  &4    	     & HHW%%% ,1HH344==/000 #jjll 	Q 	Q
U$  555*UD:Q:Q5 % T T**41AQRSSSSST '&u.>eaiPPPPP	Q 	Q d## 	L L L""4)9KKKKK	L 	LL Lr   T)r   )r   def_namer   visitingset[str] | Nonec                    | v rdS                      | g           }|r4|t                      }| |v rdS || hz  }|D ]}||vr ||          r dS dS )z<Check if a definition is used, handling circular references.TNF)r   set)rE   rF   referencing_defsreferencing_defrB   is_def_usedrC   s       r   rL   z*_single_pass_optimize.<locals>.is_def_used   s    9$$t  033HbAA $#"uuH x'' 5#xj0 (8 $ $O&h66;;'< <6  $tt5r   )NFr   )
r   r   r   r   r   r   r    r!   r	   r"   r*   )rE   r   rF   rG   r	   r   )rI   r   r<   r   r0   keysr   )r   r   r   r   defsrE   
def_schemarB   rL   rC   rD   s    ```   @@@@r   _single_pass_optimizerP      s   d  , *E  %%I4?5 5 ::gD (,"'	@L @L @L @L @L @L @L @L @L @L @L @LF v6666  %&d %&$(JJLL 	F 	F HjzHEEEEE	 	 	 	 	 	 	 	 	4 TYY[[)) 	# 	#H;x(( #"""  	&JJw%%%Mr   Nprune_paramslist[str] | Nonec                h    |pg D ]}t          | |          } |s|s|rt          | |||          } | 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   rP   )r   rQ   r   r   r   r   s         r   compress_schemarT      sl    $ # 3 3fE222  
2 
j 
&%(C!	
 
 
 Mr   )r   r   r   r   r	   r   )FFT)
r   r   r   r   r   r   r   r   r	   r   )NTTF)r   r   rQ   rR   r   r   r   r   r   r   r	   r   )
__future__r   collectionsr   r   rP   rT   r+   r   r   <module>rW      s    " " " " " " # # # # # #   . (-	j j j j j^ &*(,      r   