
    3fi]                     H   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mZ ddlmZmZ  G d	 d
e
      Z G d de      Z G d de      Z G d de      Z G d de      Z G d de
      Z G d de      Z G d de
      Z G d de      Z G d de      Zy)z(Tools for writing data to Google Sheets.    )AnyDictListOptionalType)CallbackManagerForToolRun)	BaseModelField   )SheetsBaseTool)InsertDataOptionValueInputOption)validate_range_namevalidate_spreadsheet_idc                   `    e Zd ZU dZ ed      Zeed<    eej                  d      Z
eed<   y)	WriteBaseSchemaz4Base schema for write operations with common fields.z-The ID of the Google Spreadsheet to write to.descriptionspreadsheet_idzkHow to interpret input values. 'RAW' stores values as-is. 'USER_ENTERED' parses values as if typed by user.defaultr   value_input_optionN)__name__
__module____qualname____doc__r
   r   str__annotations__r   USER_ENTEREDr        q/var/www/auto_recruiter/arenv/lib/python3.12/site-packages/langchain_google_community/sheets/write_sheet_tools.pyr   r      s=    >CNC  ,1 --@,( r!   r   c                   V    e Zd ZU dZ ed      Zeed<    ed      Ze	e	e
      ed<   y)UpdateValuesSchemaz*Input schema for `SheetsUpdateValuesTool`.z>The A1 notation of the range to update (e.g., 'Sheet1!A1:C3').r   rangezr2D array of values to write. Each inner array represents a row. Supports strings, numbers, booleans, and formulas.valuesNr   r   r   r   r
   r%   r   r   r&   r   r   r    r!   r"   r$   r$   *   s:    4TE3  $AFDcO 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<   ej                  dfded	ed
eee      dedee   deeef   fdZy)SheetsUpdateValuesToola  Tool for updating values in a single range of Google Sheets.

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

    Updates cell values in a specified range, overwriting existing data.

    !!! note "Authentication Required"

        Requires OAuth2 authentication. Use `api_resource` parameter with
        authenticated Google Sheets service.

    Tool Output:
        success (bool): Whether operation succeeded.
        spreadsheet_id (str): The spreadsheet ID.
        updated_range (str): The A1 notation of updated range.
        updated_rows (int): Number of rows updated.
        updated_columns (int): Number of columns updated.
        updated_cells (int): Total number of cells updated.

    ???+ example "Basic Usage"

        Update a range with data:

        ```python
        from langchain_google_community.sheets import SheetsUpdateValuesTool

        tool = SheetsUpdateValuesTool(api_resource=service)
        result = tool.run(
            {
                "spreadsheet_id": "1TI6vO9eGsAeXcfgEjoEYcu4RgSZCUF4vdWGLBpg9-fg",
                "range": "Sheet1!A1:C3",
                "values": [
                    ["Name", "Age", "City"],
                    ["Alice", "25", "New York"],
                    ["Bob", "30", "San Francisco"],
                ],
            }
        )
        ```

    ??? example "With Formulas"

        Update cells with formulas using `USER_ENTERED`:

        ```python
        result = tool.run(
            {
                "spreadsheet_id": "1TI6vO9eGsAeXcfgEjoEYcu4RgSZCUF4vdWGLBpg9-fg",
                "range": "Sheet1!D2:D3",
                "values": [["=SUM(B2:C2)"], ["=SUM(B3:C3)"]],
                "value_input_option": "USER_ENTERED",
            }
        )
        ```

    Raises:
        ValueError: If write permissions unavailable or validation fails.
        Exception: If `spreadsheet_id` is invalid, range is malformed, or API
            errors occur.
    sheets_update_valuesnameziUpdate values in a single range of a Google Spreadsheet. Overwrites existing data in the specified range.r   args_schemaNr   r%   r&   r   run_managerreturnc           	         | j                          	 t        |      }t        |      }| j                         }d|i}|j	                         j                         j                  |||j                  |      j                         }d||j                  d      |j                  dd      |j                  dd      |j                  dd      d	S # t        $ r}	t        d
|	       |	d}	~	ww xY w)a  Update values in a Google Spreadsheet range.

        Args:
            spreadsheet_id: ID of the spreadsheet to update.
            range: A1 notation range to update (e.g., `'Sheet1!A1:C3'`).
            values: 2D array of values to write.
            value_input_option: How to interpret input values.
            run_manager: Optional callback manager.

        Returns:
            success (bool): Whether operation succeeded.
            spreadsheet_id (str): The spreadsheet ID.
            updated_range (str): The A1 notation of updated range.
            updated_rows (int): Number of rows updated.
            updated_columns (int): Number of columns updated.
            updated_cells (int): Total number of cells updated.

        Raises:
            ValueError: If write permissions unavailable or validation fails.
            Exception: For API errors or connection issues.
        r&   )spreadsheetIdr%   valueInputOptionbodyTupdatedRangeupdatedRowsr   updatedColumnsupdatedCells)successr   updated_rangeupdated_rowsupdated_columnsupdated_cellszError updating sheet data: N)_check_write_permissionsr   r   _get_servicespreadsheetsr&   updatevalueexecuteget	Exception)
selfr   r%   r&   r   r-   servicer2   resulterrors
             r"   _runzSheetsUpdateValuesTool._run   s    < 	%%'#	N4^DN'.E '')G f%D $$&"0%7%=%=	      "0!'N!; &

=! <#)::.>#B!'NA!>   	N9%ABM	Ns   B:C 	C*C%%C*)r   r   r   r   r+   r   r   r   r$   r,   r   r	   r   r   r   r   r   r   r   rH   r    r!   r"   r)   r)   9   s    <| 'D#&	;  
 $6Ki5 0@/L/L;?CNCN CN T#Y	CN
 -CN 78CN 
c3hCNr!   r)   c                       e Zd ZU dZ ed      Zeed<    ed      Ze	e	e
      ed<    eej                  d      Zeed	<   y
)AppendValuesSchemaz*Input schema for `SheetsAppendValuesTool`.zlThe A1 notation of the table range to append to. The API will find the last row of data and append below it.r   r%   zs2D array of values to append. Each inner array represents a row. Supports strings, numbers, booleans, and formulas.r&   znHow to handle existing data. 'OVERWRITE' overwrites data after table. 'INSERT_ROWS' inserts new rows for data.r   insert_data_optionN)r   r   r   r   r
   r%   r   r   r&   r   r   r   INSERT_ROWSrK   r    r!   r"   rJ   rJ      s`    4JE3  $AFDcO  ,1 ,,7,( r!   rJ   c                       e Zd ZU dZdZeed<   dZeed<   eZ	e
e   ed<   ej                  ej                  dfded	ed
eee      dededee   deeef   fdZy)SheetsAppendValuesToola  Tool for appending values to a Google Spreadsheet table.

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

    Appends data to the end of a table, automatically finding the last row with
    data.

    !!! note "Authentication Required"

        Requires OAuth2 authentication. Use `api_resource` parameter with
        authenticated Google Sheets service.

    Tool Output:
        success (bool): Whether operation succeeded.
        spreadsheet_id (str): The spreadsheet ID.
        table_range (str): The range of the entire table.
        updated_range (str): The specific range where data was appended.
        updated_rows (int): Number of rows appended.
        updated_columns (int): Number of columns appended.
        updated_cells (int): Total number of cells updated.

    ???+ example "Basic Usage"

        Append new records to a table:

        ```python
        from langchain_google_community.sheets import SheetsAppendValuesTool

        tool = SheetsAppendValuesTool(api_resource=service)
        result = tool.run(
            {
                "spreadsheet_id": "1TI6vO9eGsAeXcfgEjoEYcu4RgSZCUF4vdWGLBpg9-fg",
                "range": "Sheet1!A1:D100",
                "values": [
                    ["Eve", "27", "Seattle", "91"],
                    ["Frank", "32", "Denver", "85"],
                ],
            }
        )
        ```

    ??? example "With Insert Rows Option"

        Insert rows instead of overwriting:

        ```python
        result = tool.run(
            {
                "spreadsheet_id": "1TI6vO9eGsAeXcfgEjoEYcu4RgSZCUF4vdWGLBpg9-fg",
                "range": "Sheet1!A1:D100",
                "values": [["New", "Record", "Data", "Here"]],
                "insert_data_option": "INSERT_ROWS",
            }
        )
        ```

    Raises:
        ValueError: If write permissions unavailable or validation fails.
        Exception: If `spreadsheet_id` is invalid, range is malformed, or API
            errors occur.
    sheets_append_valuesr+   zmAppend values to a table in a Google Spreadsheet. Automatically finds the last row and appends data below it.r   r,   Nr   r%   r&   r   rK   r-   r.   c           
      4   | j                          	 t        |      }t        |      }| j                         }d|i}|j	                         j                         j                  |||j                  |j                  |      j                         }	|	j                  di       }
d||	j                  d      |
j                  d      |
j                  dd      |
j                  d	d      |
j                  d
d      dS # t        $ r}t        d|       |d}~ww xY w)a  Append values to a Google Spreadsheet table.

        Args:
            spreadsheet_id: ID of the spreadsheet.
            range: A1 notation table range to append to.
            values: 2D array of values to append.
            value_input_option: How to interpret input values.
            insert_data_option: How to handle existing data.
            run_manager: Optional callback manager.

        Returns:
            success (bool): Whether operation succeeded.
            spreadsheet_id (str): The spreadsheet ID.
            table_range (str): The range of the entire table.
            updated_range (str): The specific range where data was appended.
            updated_rows (int): Number of rows appended.
            updated_columns (int): Number of columns appended.
            updated_cells (int): Total number of cells updated.

        Raises:
            ValueError: If write permissions unavailable or validation fails.
            Exception: For API errors or connection issues.
        r&   )r0   r%   r1   insertDataOptionr2   updatesT
tableRanger3   r4   r   r5   r6   )r7   r   table_ranger8   r9   r:   r;   zError appending sheet data: N)r<   r   r   r=   r>   r&   appendr@   rA   rB   rC   )rD   r   r%   r&   r   rK   r-   rE   r2   rF   rR   rG   s               r"   rH   zSheetsAppendValuesTool._run0  s$   B 	%%''	O4^DN'.E '')G f%D $$&"0%7%=%=%7%=%=     jjB/G  "0%zz,7!(^!< 'M1 =#*;;/?#C!(^Q!?   	O:5'BCN	Os   C'C: :	DDD)r   r   r   r   r+   r   r   r   rJ   r,   r   r	   r   r   r   rL   r   r   r   r   r   rH   r    r!   r"   rN   rN      s    =~ 'D#&	F  
 $6Ki5 0@/L/L/?/K/K;?JOJO JO T#Y	JO
 -JO -JO 78JO 
c3hJOr!   rN   c                   J    e Zd ZU dZ ed      Zeed<    ed      Zeed<   y)ClearValuesSchemaz)Input schema for `SheetsClearValuesTool`.z!The ID of the Google Spreadsheet.r   r   zlThe A1 notation of the range to clear (e.g., 'Sheet1!A1:Z100'). Only values are cleared; formatting remains.r%   N)	r   r   r   r   r
   r   r   r   r%   r    r!   r"   rW   rW     s+    3,OPNCP;E3 r!   rW   c                   n    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e   deeef   fdZy)SheetsClearValuesToola[  Tool for clearing values from a Google Spreadsheet range.

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

    Clears cell values from a specified range while preserving formatting and
    structure.

    !!! note "Authentication Required"

        Requires OAuth2 authentication. Use `api_resource` parameter with
        authenticated Google Sheets service.

    !!! info "Formatting Preserved"

        Only values are cleared. Formatting, borders, colors, fonts, and data
        validation rules remain intact.

    Tool Output:
        success (bool): Whether operation succeeded.
        spreadsheet_id (str): The spreadsheet ID.
        cleared_range (str): The A1 notation of the cleared range.

    ???+ example "Basic Usage"

        Clear a range of cells:

        ```python
        from langchain_google_community.sheets import SheetsClearValuesTool

        tool = SheetsClearValuesTool(api_resource=service)
        result = tool.run(
            {
                "spreadsheet_id": "1TI6vO9eGsAeXcfgEjoEYcu4RgSZCUF4vdWGLBpg9-fg",
                "range": "Sheet1!A1:Z100",
            }
        )
        ```

    Raises:
        ValueError: If write permissions unavailable or validation fails.
        Exception: If `spreadsheet_id` is invalid, range is malformed, or API
            errors occur.
    sheets_clear_valuesr+   zlClear values from a range in a Google Spreadsheet. Only values are cleared; formatting and structure remain.r   r,   Nr   r%   r-   r.   c                 V   | j                          	 t        |      }t        |      }| j                         }|j	                         j                         j                  ||i       j                         }d||j                  d      dS # t        $ r}t        d|       |d}~ww xY w)a>  Clear values from a Google Spreadsheet range.

        Args:
            spreadsheet_id: ID of the spreadsheet.
            range: A1 notation range to clear.
            run_manager: Optional callback manager.

        Returns:
            success (bool): Whether operation succeeded.
            spreadsheet_id (str): The spreadsheet ID.
            cleared_range (str): The A1 notation of the cleared range.

        Raises:
            ValueError: If write permissions unavailable or validation fails.
            Exception: For API errors or connection issues.
        )r0   r%   r2   TclearedRange)r7   r   cleared_rangezError clearing sheet data: N)
r<   r   r   r=   r>   r&   clearrA   rB   rC   )rD   r   r%   r-   rE   rF   rG   s          r"   rH   zSheetsClearValuesTool._run  s    . 	%%'	N4^DN'.E '')G $$&"0  
    "0!'N!;   	N9%ABM	Ns   A8B 	B(B##B()N)r   r   r   r   r+   r   r   r   rW   r,   r   r	   r   r   r   r   rH   r    r!   r"   rY   rY     sz    +Z &D#%	D  
 $5Ki4 <@	4N4N 4N 78	4N
 
c3h4Nr!   rY   c                   V    e Zd ZU dZ ed      Zeed<    ed      Ze	e	e
      ed<   y)BatchUpdateDataSchemaz4Schema for a single range update in batch operation.z The A1 notation range to update.r   r%   zU2D array of values for this range. Supports strings, numbers, booleans, and formulas.r&   Nr'   r    r!   r"   r`   r`     s4    >#EFE3F#AFDcO r!   r`   c                   4    e Zd ZU dZ ed      Zee   ed<   y)BatchUpdateValuesSchemaz/Input schema for `SheetsBatchUpdateValuesTool`.z%List of range/values pairs to update.r   dataN)	r   r   r   r   r
   rc   r   r`   r   r    r!   r"   rb   rb     s    9(-;)D$$
% r!   rb   c                       e Zd ZU dZdZeed<   dZeed<   eZ	e
e   ed<   ej                  dfded	eeeef      d
edee   deeef   f
dZy)SheetsBatchUpdateValuesToola	  Tool for batch updating multiple ranges in Google Sheets efficiently.

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

    Updates multiple ranges in a single API call, dramatically improving
    efficiency.

    Tool Output:
        success (bool): Whether operation succeeded.
        spreadsheet_id (str): The spreadsheet ID.
        total_updated_ranges (int): Number of ranges updated.
        total_updated_cells (int): Total cells updated across all ranges.
        total_updated_rows (int): Total rows updated.
        total_updated_columns (int): Total columns updated.
        responses (list): Individual results for each range with `updated_range`
            and `updated_cells`.

    ???+ example "Basic Usage"

        Update multiple ranges in one call:

        ```python
        from langchain_google_community.sheets import SheetsBatchUpdateValuesTool

        tool = SheetsBatchUpdateValuesTool(api_resource=service)
        result = tool.run(
            {
                "spreadsheet_id": "1TI6vO9eGsAeXcfgEjoEYcu4RgSZCUF4vdWGLBpg9-fg",
                "data": [
                    {
                        "range": "Sheet1!G1:G3",
                        "values": [["Status"], ["Active"], ["Active"]],
                    },
                    {"range": "Sheet1!H1:H3", "values": [["Country"], ["USA"]]},
                    {"range": "Sheet1!I1:I3", "values": [["Dept"], ["Eng"]]},
                ],
            }
        )
        ```

    ??? example "Update Multiple Sheets"

        Update ranges across different sheets:

        ```python
        result = tool.run(
            {
                "spreadsheet_id": "1TI6vO9eGsAeXcfgEjoEYcu4RgSZCUF4vdWGLBpg9-fg",
                "data": [
                    {
                        "range": "Sheet1!A1:A5",
                        "values": [["Data1"], ["Data2"], ["Data3"]],
                    },
                    {"range": "Sheet2!B1:B3", "values": [["Value1"], ["Value2"]]},
                ],
                "value_input_option": "USER_ENTERED",
            }
        )
        ```

    Raises:
        ValueError: If write permissions unavailable or validation fails.
        Exception: If `spreadsheet_id` is invalid, any range is malformed, or
            API errors occur.
    sheets_batch_update_valuesr+   zoBatch update multiple ranges in a Google Spreadsheet efficiently. Updates multiple ranges in a single API call.r   r,   Nr   rc   r   r-   r.   c                 "   | j                          	 t        |      }|st        d      | j                  |      }g }|D ]C  }|j	                  d      }|j	                  d      }	t        |       |j                  ||	d       E | j                         }
|j                  |d}|
j                         j                         j                  ||      j                         }|j	                  dg       }t        d |D              }t        d	 |D              }t        d
 |D              }d|t        |      ||||D cg c]&  }|j	                  d      |j	                  dd      d( c}dS c c}w # t        $ r}t        d|       |d}~ww xY w)a  Batch update multiple ranges in a Google Spreadsheet.

        Args:
            spreadsheet_id: ID of the spreadsheet.
            data: List of range/values pairs to update.
            value_input_option: How to interpret input values.
            run_manager: Optional callback manager.

        Returns:
            success (bool): Whether operation succeeded.
            spreadsheet_id (str): The spreadsheet ID.
            total_updated_ranges (int): Number of ranges updated.
            total_updated_cells (int): Total cells updated.
            total_updated_rows (int): Total rows updated.
            total_updated_columns (int): Total columns updated.
            responses (list): Individual results for each range.

        Raises:
            ValueError: If write permissions unavailable, validation fails, or
                data list is empty.
            Exception: For API errors or connection issues.
        z$At least one range must be specifiedr%   r&   )r%   r&   )r1   rc   )r0   r2   	responsesc              3   @   K   | ]  }|j                  d d        yw)r6   r   NrB   .0responses     r"   	<genexpr>z3SheetsBatchUpdateValuesTool._run.<locals>.<genexpr>  s       &4<^Q/&   c              3   @   K   | ]  }|j                  d d        yw)r4   r   Nrj   rk   s     r"   rn   z3SheetsBatchUpdateValuesTool._run.<locals>.<genexpr>  s       %3;]A.%ro   c              3   @   K   | ]  }|j                  d d        yw)r5   r   Nrj   rk   s     r"   rn   z3SheetsBatchUpdateValuesTool._run.<locals>.<genexpr>  s!      (6>-q1(ro   Tr3   r6   r   )r8   r;   )r7   r   total_updated_rangestotal_updated_cellstotal_updated_rowstotal_updated_columnsrh   z!Error batch updating sheet data: N)r<   r   
ValueError_convert_to_dict_listrB   r   rU   r=   r@   r>   r&   batchUpdaterA   sumlenrC   )rD   r   rc   r   r-   
data_dictsvalue_ranges	item_dict
range_namer&   rE   r2   rF   rh   rs   rt   ru   rrG   s                      r"   rH   z SheetsBatchUpdateValuesTool._rund  s   < 	%%'A	T4^DN  !GHH 33D9JL' M	&]]73
"x0 $J/##jF$KLM '')G );(@(@,WD $$&>E	  

;3I"% &@I& # "% %?H% " %( (BK( %!
  "0(+I':&8)> '
  *+~)>)*~q)A   	T?wGHeS	Ts*   D*E1 <+E,'E1 ,E1 1	F:F		F)r   r   r   r   r+   r   r   r   rb   r,   r   r	   r   r   r   r   r   r   r   rH   r    r!   r"   re   re     s    AF -D#,	8  
 $;Ki: 0@/L/L;?aTaT 4S>"aT -	aT
 78aT 
c3haTr!   re   N)r   typingr   r   r   r   r   langchain_core.callbacksr   pydanticr	   r
   baser   enumsr   r   utilsr   r   r   r$   r)   rJ   rN   rW   rY   r`   rb   re   r    r!   r"   <module>r      s    . 2 2 > %   5i , KN^ KNf 6SO^ SOv
	 
kNN kNf
I 
o nT. nTr!   