
    3fi2                         d Z ddlmZmZmZmZmZ ddlmZ ddl	m
Z
mZ ddlmZ ddlmZ  G d d	e
      Z G d
 de      Zy)zETool for retrieving Google Sheets metadata and structure information.    )AnyDictListOptionalType)CallbackManagerForToolRun)	BaseModelField   )SheetsBaseTool)validate_spreadsheet_idc                       e Zd ZU dZ edd      Zeed<    edd      Ze	ed	<    edd
      Z
e	ed<    edd      Ze	ed<    edd      Zeee      ed<    edd      Zee   ed<   y)GetSpreadsheetInfoSchemaz0Input schema for `SheetsGetSpreadsheetInfoTool`..zjThe ID of the Google Spreadsheet to get information about. Can be extracted from URL or provided directly.)descriptionspreadsheet_idFzyWhether to include detailed grid data (cell properties, formatting). Note: This can significantly increase response size.)defaultr   include_grid_datazNWhether to include cell formatting information when include_grid_data is True.include_formattingzHWhether to include data validation rules when include_grid_data is True.include_validationNzLSpecific ranges to get information about. If None, gets info for all sheets.rangesz}Specific fields to return (e.g., 'sheets.properties.title,sheets.properties.sheetId'). If None, returns all available fields.fields)__name__
__module____qualname____doc__r
   r   str__annotations__r   boolr   r   r   r   r   r        t/var/www/auto_recruiter/arenv/lib/python3.12/site-packages/langchain_google_community/sheets/get_spreadsheet_info.pyr   r      s    ::NC  $Ct   %%    %%   #(-#FHT#Y  "1FHSM r    r   c                      e Zd ZU dZdZeed<   dZeed<   eZ	e
e   ed<   	 	 	 	 	 	 dded	ed
ededeee      dee   dee   deeef   fdZ	 	 dded
ededefdZdee   deee      fdZdee   deee      fdZdee   deee      fdZy)SheetsGetSpreadsheetInfoToola4	  Tool for retrieving Google Sheets metadata and structure information.

    Inherits from
    [`SheetsBaseTool`][langchain_google_community.sheets.base.SheetsBaseTool].

    Retrieves spreadsheet properties, sheet details, named ranges, and organizational
    structure. Essential for understanding spreadsheet contents before reading data.

    Tool Output:
        success (bool): Whether operation succeeded.
        spreadsheet_id (str): The spreadsheet ID.
        title (str): Spreadsheet title.
        locale (str): Spreadsheet locale (e.g., 'en_US').
        time_zone (str): Spreadsheet timezone (e.g., 'America/New_York').
        auto_recalc (str): Auto-recalculation setting.
        default_format (dict): Default cell format.
        sheets (list): List of sheet information with properties.
        named_ranges (list): List of named ranges with locations.
        developer_metadata (list): Developer metadata entries.
        grid_data (list): Detailed cell data (when `include_grid_data=True`).

    ??? example "Basic Usage"

        Get basic spreadsheet information:

        ```python
        from langchain_google_community.sheets import SheetsGetSpreadsheetInfoTool

        tool = SheetsGetSpreadsheetInfoTool(api_key="your_api_key")
        result = tool.run(
            {"spreadsheet_id": "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms"}
        )
        print(f"Title: {result['title']}")
        print(f"Sheets: {[s['title'] for s in result['sheets']]}")
        ```

    ??? example "With Specific Fields"

        Get only specific fields to reduce response size:

        ```python
        result = tool.run(
            {
                "spreadsheet_id": "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms",
                "fields": "properties.title,sheets.properties",
            }
        )
        ```

    ??? example "Include Grid Data"

        Get detailed cell data and formatting:

        ```python
        result = tool.run(
            {
                "spreadsheet_id": "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms",
                "include_grid_data": True,
                "include_formatting": True,
                "ranges": ["Sheet1!A1:D10"],
            }
        )
        ```

    Raises:
        ValueError: If spreadsheet_id is invalid.
        Exception: For API errors or connection issues.
    sheets_get_spreadsheet_infonamea  Retrieve comprehensive metadata information from Google Sheets including spreadsheet properties, sheet details, named ranges, and organizational structure. Essential for understanding spreadsheet contents before reading data and exploring spreadsheet structure.r   args_schemaNr   r   r   r   r   r   run_managerreturnc                 0   	 t        |      }| j                         }	||d}
|r||
d<   |r||
d<    |	j                         j                  di |
j	                         }| j                  |||      }d|d<   |S # t        $ r}t        d|       |d}~ww xY w)	aP  Get spreadsheet metadata and structure information.

        Args:
            spreadsheet_id: ID of the spreadsheet to retrieve information about.
            include_grid_data: Whether to include detailed grid data.
            include_formatting: Whether to include cell formatting.
            include_validation: Whether to include data validation rules.
            ranges: Specific ranges to get information about.
            fields: Specific fields to return (reduces response size).
            run_manager: Optional callback manager.

        Returns:
            success (bool): Whether operation succeeded.
            spreadsheet_id (str): The spreadsheet ID.
            title (str): Spreadsheet title.
            locale (str): Spreadsheet locale.
            time_zone (str): Spreadsheet timezone.
            auto_recalc (str): Auto-recalculation setting.
            default_format (dict): Default cell format.
            sheets (list): List of sheet information with properties.
            named_ranges (list): List of named ranges with locations.
            developer_metadata (list): Developer metadata entries.
            grid_data (list): Detailed cell data (when `include_grid_data=True`).

        Raises:
            ValueError: If `spreadsheet_id` is invalid.
            Exception: For API errors or connection issues.
        )spreadsheetIdincludeGridDatar   r   Tsuccessz Error getting spreadsheet info: Nr   )r   _get_servicespreadsheetsgetexecute_process_spreadsheet_info	Exception)selfr   r   r   r   r   r   r'   validated_spreadsheet_idservicerequest_paramsresponseprocessed_infoerrors                 r!   _runz!SheetsGetSpreadsheetInfoTool._run   s    L 	S'>~'N$ '')G ":#4N
 +1x(+1x( 2w++-11CNCKKMH ";;,.@N
 )-N9%!! 	S>ugFGUR	Ss   A5A8 8	BBBr7   c                    |j                  d      |j                  di       j                  d      |j                  di       j                  d      |j                  di       j                  d      |j                  di       j                  d      |j                  di       j                  di       g g g d	}|j                  d	g       }|D ]S  }|j                  di       j                  d
      |j                  di       j                  d      |j                  di       j                  d      |j                  di       j                  di       |j                  di       j                  di       |j                  di       j                  dd      |j                  di       j                  dd      d}d|v r| j                  |d         |d<   |rd|v r| j                  |d         |d<   |rd|v r| j                  |d         |d<   |d	   j	                  |       V |j                  dg       }|D ]I  }	|	j                  d      |	j                  d      |	j                  d      d}
|d   j	                  |
       K |j                  dg       }|D ]j  }|j                  d      |j                  d      |j                  d      |j                  d       |j                  d!i       d"}|d#   j	                  |       l |S )$z*Process the raw spreadsheet info response.r*   
propertiestitlelocaletimeZone
autoRecalcdefaultFormat)	r   r=   r>   	time_zoneauto_recalcdefault_formatsheetsnamed_rangesdeveloper_metadatarE   sheetId	sheetTypegridPropertiestabColorhiddenFrightToLeft)sheet_idr=   
sheet_typegrid_properties	tab_colorrL   right_to_leftdata	grid_data
formatting
validationnamedRangesr%   rangenamedRangeId)r%   rX   named_range_idrF   developerMetadata
metadataIdkeyvalue
visibilitylocation)metadata_idr]   r^   r_   r`   rG   )r/   _process_grid_data_extract_formatting_extract_validationappend)r3   r7   r   r   spreadsheet_inforE   sheet
sheet_inforF   named_range
range_inforG   metadatametadata_infos                 r!   r1   z6SheetsGetSpreadsheetInfoTool._process_spreadsheet_info   s    'll?;\\,377@ll<488B!lB7;;JG#<<b9==lK&ll<<@@RTU"$

 h+ 	:E!IIlB7;;IF<488A#iib9==kJ#(99\2#>#B#B$b$ #YY|R8<<ZL))L"599(EJ!&<!<!@!@PU!V
J *.*A*A%-*P
;' "fo+/+C+CE&M+R
<( "fo+/+C+CE&M+R
<(X&--j93	:8  ||M26' 	@K#/$1"-//."AJ
 ^,33J?	@ &\\*=rB* 	IH'||L9||E*!g.&ll<8$LLR8M 1299-H	I  r    rT   c                     |sg S g }|D ]m  }|j                  dg       xs g D ]R  }g }|j                  dg       xs g D ]$  }| j                  |      }|j                  |       & |j                  |       T o |S )zProcess ALL grid data segments using simplified patterns.

        Now processes all GridData segments to prevent data loss when the API
        returns multiple segments.
        rowDatavalues)r/   _safe_get_cell_valuere   )r3   rT   resultgridrow_data
row_values	cell_datar^   s           r!   rb   z/SheetsGetSpreadsheetInfoTool._process_grid_data  s     I #% 	*D HHY39r *(*
!)h!;!Ar -I 55i@E%%e,- j)*	* r    c                    |sg S g }|D ]  }|j                  dg       xs g D ]f  }g }|j                  dg       xs g D ]8  }|j                  di       |j                  di       d}|j                  |       : |j                  |       h  |S )z;Extract cell formatting information from ALL grid segments.rn   ro   userEnteredFormateffectiveFormat)user_entered_formateffective_formatr/   re   )r3   rT   formatting_inforr   rs   row_formattingru   cell_formattings           r!   rc   z0SheetsGetSpreadsheetInfoTool._extract_formatting/  s    I -/ 		7D HHY39r 7-/!)h!;!Ar ;I/8}}=PRT/U,5MM:KR,P'O #))/:;  &&~67		7 r    c                     |sg S g }|D ]  }|j                  dg       xs g D ]g  }g }|j                  dg       xs g D ]9  }|j                  di       }|r|j                  |       )|j                  i        ; |j                  |       i  |S )z5Extract data validation rules from ALL grid segments.rn   ro   dataValidationr{   )r3   rT   validation_inforr   rs   row_validationru   validation_rules           r!   rd   z0SheetsGetSpreadsheetInfoTool._extract_validationC  s    I -/ 		7D HHY39r 7-/!)h!;!Ar 2I&/mm4Db&IO&&--o>&--b12  &&~67		7 r    )FFFNNN)FF)r   r   r   r   r%   r   r   r   r   r&   r   r   r   r   r   r   r   r:   dictr1   rb   rc   rd   r   r    r!   r#   r#   7   sf   CJ .D#-	4   3KK./J
 #(#(#(&* $;?FSFS  FS !	FS
 !FS c#FS FS 78FS 
c3hFSV $)#(	G G  !G  !	G 
 
G RDJ 4S	? ,T$Z Dd<L (T$Z Dd<L r    r#   N)r   typingr   r   r   r   r   langchain_core.callbacksr   pydanticr	   r
   baser   utilsr   r   r#   r   r    r!   <module>r      s5    K 2 2 > %   *(y (V^> ^r    