@mutallip/google-workspace-mcp 0.0.0-stage → 2.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +353 -2
  3. package/README.npm.md +34 -0
  4. package/auth/__init__.py +1 -0
  5. package/auth/auth_info_middleware.py +419 -0
  6. package/auth/client_secrets.py +76 -0
  7. package/auth/credential_store.py +598 -0
  8. package/auth/external_oauth_provider.py +369 -0
  9. package/auth/gateway_identity.py +164 -0
  10. package/auth/google_auth.py +1550 -0
  11. package/auth/google_oauth_provider.py +20 -0
  12. package/auth/mcp_session_middleware.py +95 -0
  13. package/auth/oauth21_session_store.py +1332 -0
  14. package/auth/oauth_callback_server.py +466 -0
  15. package/auth/oauth_config.py +693 -0
  16. package/auth/oauth_proxy_config.py +122 -0
  17. package/auth/oauth_responses.py +230 -0
  18. package/auth/oauth_types.py +92 -0
  19. package/auth/permissions.py +330 -0
  20. package/auth/port_resolver.py +153 -0
  21. package/auth/request_identity.py +89 -0
  22. package/auth/scopes.py +369 -0
  23. package/auth/service_decorator.py +1109 -0
  24. package/bin/google-workspace-mcp.cjs +123 -0
  25. package/core/__init__.py +1 -0
  26. package/core/api_enablement.py +108 -0
  27. package/core/attachment_storage.py +496 -0
  28. package/core/camel_case_middleware.py +98 -0
  29. package/core/cli.py +161 -0
  30. package/core/comments.py +609 -0
  31. package/core/config.py +57 -0
  32. package/core/context.py +43 -0
  33. package/core/file_limits.py +632 -0
  34. package/core/gcs_attachment_storage.py +253 -0
  35. package/core/http_utils.py +339 -0
  36. package/core/log_formatter.py +270 -0
  37. package/core/portable_schema_middleware.py +67 -0
  38. package/core/server.py +1192 -0
  39. package/core/startup_ui.py +239 -0
  40. package/core/storage.py +23 -0
  41. package/core/telemetry.py +194 -0
  42. package/core/tool_descriptions.py +19 -0
  43. package/core/tool_registry.py +311 -0
  44. package/core/tool_tier_loader.py +197 -0
  45. package/core/tool_tiers.yaml +179 -0
  46. package/core/toolset_header_middleware.py +67 -0
  47. package/core/utils.py +1537 -0
  48. package/core/valkey_storage.py +271 -0
  49. package/core/warning_filters.py +19 -0
  50. package/fastmcp_server.py +198 -0
  51. package/gappsscript/README.md +512 -0
  52. package/gappsscript/TESTING.md +254 -0
  53. package/gappsscript/__init__.py +0 -0
  54. package/gappsscript/apps_script_tools.py +1940 -0
  55. package/gcalendar/__init__.py +1 -0
  56. package/gcalendar/calendar_helpers.py +1323 -0
  57. package/gcalendar/calendar_tools.py +2252 -0
  58. package/gchat/__init__.py +7 -0
  59. package/gchat/chat_helpers.py +410 -0
  60. package/gchat/chat_tools.py +798 -0
  61. package/gcontacts/__init__.py +1 -0
  62. package/gcontacts/contacts_helpers.py +765 -0
  63. package/gcontacts/contacts_tools.py +1685 -0
  64. package/gdocs/__init__.py +0 -0
  65. package/gdocs/docs_anchors.py +163 -0
  66. package/gdocs/docs_comments.py +89 -0
  67. package/gdocs/docs_helpers.py +2201 -0
  68. package/gdocs/docs_links.py +87 -0
  69. package/gdocs/docs_markdown.py +828 -0
  70. package/gdocs/docs_markdown_writer.py +592 -0
  71. package/gdocs/docs_plain_text.py +463 -0
  72. package/gdocs/docs_structure.py +621 -0
  73. package/gdocs/docs_tables.py +425 -0
  74. package/gdocs/docs_tools.py +3300 -0
  75. package/gdocs/managers/__init__.py +18 -0
  76. package/gdocs/managers/batch_operation_manager.py +1694 -0
  77. package/gdocs/managers/header_footer_manager.py +526 -0
  78. package/gdocs/managers/table_operation_manager.py +488 -0
  79. package/gdocs/managers/validation_manager.py +1504 -0
  80. package/gdocs/operation_schemas.py +594 -0
  81. package/gdrive/__init__.py +0 -0
  82. package/gdrive/drive_helpers.py +1738 -0
  83. package/gdrive/drive_tools.py +3085 -0
  84. package/gforms/__init__.py +3 -0
  85. package/gforms/forms_tools.py +575 -0
  86. package/gmail/__init__.py +1 -0
  87. package/gmail/gmail_helpers.py +2107 -0
  88. package/gmail/gmail_tools.py +4895 -0
  89. package/gmail/gmail_web_mime.py +441 -0
  90. package/gsearch/__init__.py +0 -0
  91. package/gsearch/search_tools.py +253 -0
  92. package/gsheets/__init__.py +31 -0
  93. package/gsheets/sheets_helpers.py +2236 -0
  94. package/gsheets/sheets_tools.py +3280 -0
  95. package/gslides/__init__.py +0 -0
  96. package/gslides/slides_digest.py +390 -0
  97. package/gslides/slides_helpers.py +392 -0
  98. package/gslides/slides_markup.py +770 -0
  99. package/gslides/slides_tools.py +376 -0
  100. package/gtasks/__init__.py +5 -0
  101. package/gtasks/tasks_tools.py +936 -0
  102. package/main.py +1170 -0
  103. package/package.json +43 -4
  104. package/pyproject.toml +173 -0
  105. package/uv.lock +2504 -0
@@ -0,0 +1,2236 @@
1
+ """
2
+ Google Sheets Helper Functions
3
+
4
+ Shared utilities for Google Sheets operations including A1 parsing and
5
+ conditional formatting helpers.
6
+ """
7
+
8
+ import asyncio
9
+ import csv
10
+ import io
11
+ import json
12
+ import logging
13
+ import math
14
+ import re
15
+ from pathlib import Path
16
+ from typing import Any, List, Optional, Union
17
+
18
+ from core.utils import NotARegularFileError, UserInputError, open_validated_file
19
+
20
+ logger = logging.getLogger(__name__)
21
+
22
+ MAX_GRID_METADATA_CELLS = 5000
23
+
24
+ # Cap rows fetched by read_sheet_values before calling values().get.
25
+ # Matches the tool default range (A1:Z1000). Open-ended or oversized A1
26
+ # ranges otherwise materialize the full sheet into memory.
27
+ MAX_READ_SHEET_ROWS = 1000
28
+
29
+ A1_PART_REGEX = re.compile(r"^([A-Za-z]*)(\d*)$")
30
+ SHEET_TITLE_SAFE_RE = re.compile(r"^[A-Za-z0-9_]+$")
31
+ COLUMN_LETTER_REGEX = re.compile(r"^[A-Za-z]+$")
32
+ QUOTED_SHEET_ONLY_REGEX = re.compile(r"^'(?:[^']|'')+'$")
33
+ MERGE_TYPES = ("MERGE_ALL", "MERGE_COLUMNS", "MERGE_ROWS")
34
+ PASTE_TYPES = (
35
+ "PASTE_NORMAL",
36
+ "PASTE_VALUES",
37
+ "PASTE_FORMAT",
38
+ "PASTE_NO_BORDERS",
39
+ "PASTE_FORMULA",
40
+ "PASTE_DATA_VALIDATION",
41
+ "PASTE_CONDITIONAL_FORMATTING",
42
+ )
43
+
44
+
45
+ def _column_to_index(column: str) -> Optional[int]:
46
+ """Convert column letters (A, B, AA) to zero-based index."""
47
+ if not column or not COLUMN_LETTER_REGEX.fullmatch(column):
48
+ return None
49
+ result = 0
50
+ for char in column.upper():
51
+ result = result * 26 + (ord(char) - ord("A") + 1)
52
+ return result - 1
53
+
54
+
55
+ def _parse_a1_part(
56
+ part: str, pattern: re.Pattern[str] = A1_PART_REGEX
57
+ ) -> tuple[Optional[int], Optional[int]]:
58
+ """
59
+ Parse a single A1 part like 'B2' or 'C' into zero-based column/row indexes.
60
+ Supports anchors like '$A$1' by stripping the dollar signs.
61
+ """
62
+ clean_part = part.replace("$", "")
63
+ match = pattern.fullmatch(clean_part)
64
+ if not match:
65
+ raise UserInputError(f"Invalid A1 range part: '{part}'.")
66
+ col_letters, row_digits = match.groups()
67
+ col_idx = _column_to_index(col_letters) if col_letters else None
68
+ row_idx = int(row_digits) - 1 if row_digits else None
69
+ return col_idx, row_idx
70
+
71
+
72
+ def _split_sheet_and_range(range_name: str) -> tuple[Optional[str], str]:
73
+ """
74
+ Split an A1 notation into (sheet_name, range_part), handling quoted sheet names.
75
+
76
+ Examples:
77
+ - "Sheet1!A1:B2" -> ("Sheet1", "A1:B2")
78
+ - "'My Sheet'!$A$1:$B$10" -> ("My Sheet", "$A$1:$B$10")
79
+ - "A1:B2" -> (None, "A1:B2")
80
+ """
81
+ if "!" not in range_name:
82
+ return None, range_name
83
+
84
+ if range_name.startswith("'"):
85
+ closing = range_name.find("'!")
86
+ if closing != -1:
87
+ sheet_name = range_name[1:closing].replace("''", "'")
88
+ a1_range = range_name[closing + 2 :]
89
+ return sheet_name, a1_range
90
+
91
+ sheet_name, a1_range = range_name.split("!", 1)
92
+ return sheet_name.strip().strip("'"), a1_range
93
+
94
+
95
+ def _format_a1_part(col_idx: Optional[int], row_idx: Optional[int]) -> str:
96
+ """Build an A1 cell/partial reference from zero-based indexes."""
97
+ col = _index_to_column(col_idx) if col_idx is not None else ""
98
+ row = str(row_idx + 1) if row_idx is not None else ""
99
+ if not col and not row:
100
+ raise UserInputError("A1 range part must include a column and/or row.")
101
+ return f"{col}{row}"
102
+
103
+
104
+ def _format_read_clamp_note(range_name: str, clamped_range: str, max_rows: int) -> str:
105
+ """Describe a rewritten read range and how to continue paging."""
106
+ return (
107
+ f"\n\nNote: Requested range '{range_name}' was clamped to '{clamped_range}' "
108
+ f"(max {max_rows} rows per read). Request a later row window to continue."
109
+ )
110
+
111
+
112
+ def _clamp_a1_read_rows(
113
+ range_name: str, max_rows: int = MAX_READ_SHEET_ROWS
114
+ ) -> tuple[str, Optional[str]]:
115
+ """
116
+ Rewrite an A1 range so it spans at most ``max_rows`` rows.
117
+
118
+ Open-ended ranges (e.g. ``A:Z``, ``Sheet1!A1:Z``) and quoted whole-sheet
119
+ references (e.g. ``'My Sheet'``) are closed to a finite end row. Oversized
120
+ finite ranges are truncated from the start row. Bare identifiers are
121
+ returned unchanged because they can refer to named ranges.
122
+
123
+ Returns:
124
+ (range_for_api, note): ``note`` is set when the range was rewritten.
125
+ """
126
+ if max_rows < 1:
127
+ raise ValueError(f"max_rows must be >= 1, got {max_rows}")
128
+
129
+ # A quoted sheet title without coordinates unambiguously addresses the
130
+ # entire sheet. Bare identifiers are intentionally not handled here:
131
+ # Google Sheets resolves them as named ranges when a matching name exists.
132
+ if QUOTED_SHEET_ONLY_REGEX.fullmatch(range_name):
133
+ clamped_range = f"{range_name}!1:{max_rows}"
134
+ return clamped_range, _format_read_clamp_note(
135
+ range_name, clamped_range, max_rows
136
+ )
137
+
138
+ sheet_name, a1_range = _split_sheet_and_range(range_name)
139
+ if not a1_range:
140
+ return range_name, None
141
+
142
+ try:
143
+ if ":" in a1_range:
144
+ start, end = a1_range.split(":", 1)
145
+ else:
146
+ # Bare identifiers without a row (e.g. named ranges) are not A1
147
+ # coordinates we can safely rewrite.
148
+ start = end = a1_range
149
+ start_col, start_row = _parse_a1_part(start)
150
+ end_col, end_row = _parse_a1_part(end)
151
+ except UserInputError:
152
+ logger.warning(
153
+ "Cannot clamp non-A1 sheet range %r; fetching as requested",
154
+ range_name,
155
+ )
156
+ return range_name, None
157
+
158
+ if ":" not in a1_range and start_row is None:
159
+ return range_name, None
160
+
161
+ effective_start = start_row if start_row is not None else 0
162
+ max_end_row = effective_start + max_rows - 1
163
+
164
+ clamped = False
165
+ if start_row is None:
166
+ start_row = effective_start
167
+ clamped = True
168
+ if end_row is None or end_row > max_end_row:
169
+ end_row = max_end_row
170
+ clamped = True
171
+
172
+ if not clamped:
173
+ return range_name, None
174
+
175
+ range_ref = (
176
+ _format_a1_part(start_col, start_row)
177
+ if start_col == end_col and start_row == end_row
178
+ else f"{_format_a1_part(start_col, start_row)}:{_format_a1_part(end_col, end_row)}"
179
+ )
180
+ if sheet_name is not None:
181
+ clamped_range = f"{_quote_sheet_title_for_a1(sheet_name)}!{range_ref}"
182
+ else:
183
+ clamped_range = range_ref
184
+
185
+ note = _format_read_clamp_note(range_name, clamped_range, max_rows)
186
+ return clamped_range, note
187
+
188
+
189
+ def _parse_a1_range(range_name: str, sheets: List[dict]) -> dict:
190
+ """
191
+ Convert an A1-style range (with optional sheet name) into a GridRange.
192
+
193
+ Falls back to the first sheet if none is provided.
194
+ """
195
+ sheet_name, a1_range = _split_sheet_and_range(range_name)
196
+
197
+ if not sheets:
198
+ raise UserInputError("Spreadsheet has no sheets.")
199
+
200
+ target_sheet = None
201
+ if sheet_name:
202
+ for sheet in sheets:
203
+ if sheet.get("properties", {}).get("title") == sheet_name:
204
+ target_sheet = sheet
205
+ break
206
+ if target_sheet is None:
207
+ available_titles = [
208
+ sheet.get("properties", {}).get("title", "Untitled") for sheet in sheets
209
+ ]
210
+ available_list = ", ".join(available_titles) if available_titles else "none"
211
+ raise UserInputError(
212
+ f"Sheet '{sheet_name}' not found in spreadsheet. Available sheets: {available_list}."
213
+ )
214
+ else:
215
+ target_sheet = sheets[0]
216
+
217
+ props = target_sheet.get("properties", {})
218
+ sheet_id = props.get("sheetId")
219
+
220
+ if not a1_range:
221
+ raise UserInputError("A1-style range must not be empty (e.g., 'A1', 'A1:B10').")
222
+
223
+ if ":" in a1_range:
224
+ start, end = a1_range.split(":", 1)
225
+ else:
226
+ start = end = a1_range
227
+
228
+ start_col, start_row = _parse_a1_part(start)
229
+ end_col, end_row = _parse_a1_part(end)
230
+
231
+ grid_range = {"sheetId": sheet_id}
232
+ if start_row is not None:
233
+ grid_range["startRowIndex"] = start_row
234
+ if start_col is not None:
235
+ grid_range["startColumnIndex"] = start_col
236
+ if end_row is not None:
237
+ grid_range["endRowIndex"] = end_row + 1
238
+ if end_col is not None:
239
+ grid_range["endColumnIndex"] = end_col + 1
240
+
241
+ return grid_range
242
+
243
+
244
+ def _parse_hex_color(color: Optional[str]) -> Optional[dict]:
245
+ """
246
+ Convert a hex color like '#RRGGBB' to Sheets API color (0-1 floats).
247
+ """
248
+ if not color:
249
+ return None
250
+
251
+ trimmed = color.strip()
252
+ if trimmed.startswith("#"):
253
+ trimmed = trimmed[1:]
254
+
255
+ if len(trimmed) != 6:
256
+ raise UserInputError(f"Color '{color}' must be in format #RRGGBB or RRGGBB.")
257
+
258
+ try:
259
+ red = int(trimmed[0:2], 16) / 255
260
+ green = int(trimmed[2:4], 16) / 255
261
+ blue = int(trimmed[4:6], 16) / 255
262
+ except ValueError as exc:
263
+ raise UserInputError(f"Color '{color}' is not valid hex.") from exc
264
+
265
+ return {"red": red, "green": green, "blue": blue}
266
+
267
+
268
+ def _build_tab_style_properties(
269
+ tab_color: Optional[str] = None,
270
+ show_gridlines: Optional[bool] = None,
271
+ ) -> tuple[dict, str, str]:
272
+ """
273
+ Build the sheet properties for manage_sheet_tab's "style" action.
274
+
275
+ Args:
276
+ tab_color: Hex color for the tab, or "none" to remove it.
277
+ show_gridlines: Whether the sheet shows gridlines.
278
+
279
+ Returns:
280
+ The properties to set (without sheetId), the fields mask, and a
281
+ short human-readable summary.
282
+ """
283
+ if tab_color is None and show_gridlines is None:
284
+ raise UserInputError("action='style' needs tab_color and/or show_gridlines.")
285
+
286
+ properties: dict = {}
287
+ fields = []
288
+ parts = []
289
+ if tab_color is not None:
290
+ color = tab_color.strip()
291
+ if not color:
292
+ raise UserInputError("tab_color must be a hex color (#RRGGBB) or 'none'.")
293
+ if color.lower() == "none":
294
+ # An empty colour style with the field in the mask clears it.
295
+ properties["tabColorStyle"] = {}
296
+ parts.append("removed tab color")
297
+ else:
298
+ properties["tabColorStyle"] = {"rgbColor": _parse_hex_color(color)}
299
+ parts.append(f"tab color #{color.lstrip('#').upper()}")
300
+ fields.append("tabColorStyle")
301
+ if show_gridlines is not None:
302
+ properties["gridProperties"] = {"hideGridlines": not show_gridlines}
303
+ fields.append("gridProperties.hideGridlines")
304
+ parts.append("gridlines shown" if show_gridlines else "gridlines hidden")
305
+ return properties, ",".join(fields), ", ".join(parts)
306
+
307
+
308
+ BORDER_SIDES = ("top", "bottom", "left", "right", "innerHorizontal", "innerVertical")
309
+ # Keys are normalized: lowercase with "_" and "-" removed, so "inner_horizontal",
310
+ # "inner-horizontal" and the API's own "innerHorizontal" all match.
311
+ BORDER_SIDE_ALIASES = {
312
+ "all": BORDER_SIDES,
313
+ "outer": ("top", "bottom", "left", "right"),
314
+ "inner": ("innerHorizontal", "innerVertical"),
315
+ "top": ("top",),
316
+ "bottom": ("bottom",),
317
+ "left": ("left",),
318
+ "right": ("right",),
319
+ "innerhorizontal": ("innerHorizontal",),
320
+ "innervertical": ("innerVertical",),
321
+ }
322
+ BORDER_SIDE_NAMES = (
323
+ "all",
324
+ "outer",
325
+ "inner",
326
+ "top",
327
+ "bottom",
328
+ "left",
329
+ "right",
330
+ "inner_horizontal",
331
+ "inner_vertical",
332
+ )
333
+ BORDER_STYLES = {"DOTTED", "DASHED", "SOLID", "SOLID_MEDIUM", "SOLID_THICK", "DOUBLE"}
334
+
335
+
336
+ def _build_update_borders_request(
337
+ borders: str,
338
+ border_style: Optional[str] = None,
339
+ border_color: Optional[str] = None,
340
+ ) -> tuple[dict, str]:
341
+ """
342
+ Build an updateBorders request. The caller sets its "range" once the
343
+ GridRange is known, so input errors surface before any API call.
344
+
345
+ Args:
346
+ borders: Comma-separated sides: all, outer, inner, top, bottom, left,
347
+ right, inner_horizontal, inner_vertical. "none" removes all borders.
348
+ border_style: One of BORDER_STYLES. Defaults to SOLID.
349
+ border_color: Hex color. Defaults to black.
350
+
351
+ Returns:
352
+ The request dict (without range) and a short human-readable summary.
353
+ """
354
+ tokens = [t.strip().lower() for t in borders.split(",") if t.strip()]
355
+ if not tokens:
356
+ raise UserInputError("borders must name at least one side.")
357
+ style_given = bool(border_style and border_style.strip())
358
+ color_given = bool(border_color and border_color.strip())
359
+
360
+ if "none" in tokens:
361
+ if tokens != ["none"]:
362
+ raise UserInputError("borders='none' cannot be combined with sides.")
363
+ if style_given or color_given:
364
+ raise UserInputError(
365
+ "borders='none' removes borders; drop border_style and border_color."
366
+ )
367
+ border: dict = {"style": "NONE"}
368
+ sides = BORDER_SIDES
369
+ summary = "borders removed"
370
+ else:
371
+ keys = [t.replace("_", "").replace("-", "") for t in tokens]
372
+ unknown = [t for t, k in zip(tokens, keys) if k not in BORDER_SIDE_ALIASES]
373
+ if unknown:
374
+ raise UserInputError(
375
+ f"Unknown border side(s) {unknown}. Use 'none' alone, or any of "
376
+ f"{list(BORDER_SIDE_NAMES)}."
377
+ )
378
+ style = border_style.strip().upper() if style_given else "SOLID"
379
+ if style not in BORDER_STYLES:
380
+ raise UserInputError(
381
+ f"border_style must be one of {sorted(BORDER_STYLES)}."
382
+ )
383
+ border = {
384
+ "style": style,
385
+ "color": _parse_hex_color(border_color)
386
+ if color_given
387
+ else {"red": 0.0, "green": 0.0, "blue": 0.0},
388
+ }
389
+ sides = [side for k in keys for side in BORDER_SIDE_ALIASES[k]]
390
+ summary = f"{style} borders ({', '.join(tokens)})"
391
+ if color_given:
392
+ summary += f" in {border_color.strip()}"
393
+
394
+ return {"updateBorders": {side: dict(border) for side in sides}}, summary
395
+
396
+
397
+ def _build_dropdown_request(
398
+ dropdown_values: Optional[List[str]] = None,
399
+ dropdown_strict: Optional[bool] = None,
400
+ clear_dropdown: Optional[bool] = None,
401
+ ) -> tuple[dict, str]:
402
+ """
403
+ Build a setDataValidation request that adds or removes a dropdown list.
404
+ The caller sets its "range" once the GridRange is known, so input errors
405
+ surface before any API call.
406
+
407
+ Args:
408
+ dropdown_values: Allowed values, shown as a dropdown (ONE_OF_LIST).
409
+ dropdown_strict: Reject values outside the list (default True). False
410
+ only shows a warning.
411
+ clear_dropdown: Remove all data validation from the range instead
412
+ (dropdowns, but also checkboxes and other rules).
413
+
414
+ Returns:
415
+ The request dict (without range) and a short human-readable summary.
416
+ """
417
+ if clear_dropdown:
418
+ if dropdown_values is not None:
419
+ raise UserInputError(
420
+ "Pass either dropdown_values or clear_dropdown, not both."
421
+ )
422
+ return {"setDataValidation": {}}, "data validation removed"
423
+
424
+ values = [str(v).strip() for v in (dropdown_values or [])]
425
+ values = [v for v in values if v]
426
+ if not values:
427
+ raise UserInputError("dropdown_values must contain at least one value.")
428
+
429
+ strict = dropdown_strict is not False
430
+ request = {
431
+ "setDataValidation": {
432
+ "rule": {
433
+ "condition": {
434
+ "type": "ONE_OF_LIST",
435
+ "values": [{"userEnteredValue": v} for v in values],
436
+ },
437
+ "strict": strict,
438
+ "showCustomUi": True,
439
+ },
440
+ }
441
+ }
442
+ summary = f"dropdown [{', '.join(values)}]"
443
+ if not strict:
444
+ summary += " (warning only)"
445
+ return request, summary
446
+
447
+
448
+ def _normalize_merge_type(
449
+ merge_cells: Optional[bool], merge_type: Optional[str]
450
+ ) -> Optional[str]:
451
+ """Return the merge type to apply, or None when the call does not merge."""
452
+ if merge_type is None:
453
+ return "MERGE_ALL" if merge_cells else None
454
+ if merge_cells is False:
455
+ raise UserInputError(
456
+ "Cannot specify merge_type when merge_cells is False (unmerging)."
457
+ )
458
+ normalized = merge_type.strip().upper()
459
+ if normalized not in MERGE_TYPES:
460
+ raise UserInputError(f"merge_type must be one of {list(MERGE_TYPES)}.")
461
+ return normalized
462
+
463
+
464
+ def _build_merge_request(grid_range: dict, range_name: str, merge_type: str) -> dict:
465
+ """Build a mergeCells request, rejecting ranges where any merge group is one cell."""
466
+ rows = grid_range.get("endRowIndex", math.inf) - grid_range.get("startRowIndex", 0)
467
+ cols = grid_range.get("endColumnIndex", math.inf) - grid_range.get(
468
+ "startColumnIndex", 0
469
+ )
470
+ group_size = {
471
+ "MERGE_ALL": rows * cols,
472
+ "MERGE_COLUMNS": rows,
473
+ "MERGE_ROWS": cols,
474
+ }[merge_type]
475
+ if group_size < 2:
476
+ raise UserInputError(
477
+ f"Cannot apply {merge_type} to '{range_name}': each merged group "
478
+ "must span at least 2 cells."
479
+ )
480
+ return {"mergeCells": {"range": grid_range, "mergeType": merge_type}}
481
+
482
+
483
+ def _index_to_column(index: int) -> str:
484
+ """
485
+ Convert a zero-based column index to column letters (0 -> A, 25 -> Z, 26 -> AA).
486
+ """
487
+ if index < 0:
488
+ raise UserInputError(f"Column index must be non-negative, got {index}.")
489
+
490
+ result = []
491
+ index += 1 # Convert to 1-based for calculation
492
+ while index:
493
+ index, remainder = divmod(index - 1, 26)
494
+ result.append(chr(ord("A") + remainder))
495
+ return "".join(reversed(result))
496
+
497
+
498
+ def _quote_sheet_title_for_a1(sheet_title: str) -> str:
499
+ """
500
+ Quote a sheet title for use in A1 notation if necessary.
501
+
502
+ If the sheet title contains special characters or spaces, it is wrapped in single quotes.
503
+ Any single quotes in the title are escaped by doubling them, as required by Google Sheets.
504
+ """
505
+ if SHEET_TITLE_SAFE_RE.fullmatch(sheet_title or ""):
506
+ return sheet_title
507
+ escaped = (sheet_title or "").replace("'", "''")
508
+ return f"'{escaped}'"
509
+
510
+
511
+ def _format_a1_cell(sheet_title: str, row_index: int, col_index: int) -> str:
512
+ """
513
+ Format a cell reference in A1 notation given a sheet title and zero-based row/column indices.
514
+
515
+ Args:
516
+ sheet_title: The title of the sheet.
517
+ row_index: Zero-based row index (0 for first row).
518
+ col_index: Zero-based column index (0 for column A).
519
+
520
+ Returns:
521
+ A string representing the cell reference in A1 notation, e.g., 'Sheet1!B2'.
522
+ """
523
+ return f"{_quote_sheet_title_for_a1(sheet_title)}!{_index_to_column(col_index)}{row_index + 1}"
524
+
525
+
526
+ def _coerce_int(value: object, default: int = 0) -> int:
527
+ """
528
+ Safely convert a value to an integer, returning a default value if conversion fails.
529
+
530
+ Args:
531
+ value: The value to convert to int.
532
+ default: The value to return if conversion fails (default is 0).
533
+
534
+ Returns:
535
+ The integer value of `value`, or `default` if conversion fails.
536
+ """
537
+ try:
538
+ return int(value) # type: ignore[arg-type]
539
+ except (TypeError, ValueError):
540
+ return default
541
+
542
+
543
+ def _is_sheets_error_token(value: object) -> bool:
544
+ """
545
+ Detect whether a cell value represents a Google Sheets error token (e.g., #ERROR!, #NAME?, #REF!, #N/A).
546
+
547
+ Returns True if the value is a string that starts with '#' and ends with '!' or '?', or is exactly '#N/A'.
548
+ """
549
+ if not isinstance(value, str):
550
+ return False
551
+ candidate = value.strip()
552
+ if not candidate.startswith("#"):
553
+ return False
554
+ upper_candidate = candidate.upper()
555
+ if upper_candidate == "#N/A":
556
+ return True
557
+ return upper_candidate.endswith(("!", "?"))
558
+
559
+
560
+ def _values_contain_sheets_errors(values: List[List[object]]) -> bool:
561
+ """
562
+ Check whether a 2D array of cell values contains any Google Sheets error tokens.
563
+
564
+ Args:
565
+ values: A 2D list of cell values (as returned from the Sheets API).
566
+
567
+ Returns:
568
+ True if any cell contains a Google Sheets error token, False otherwise.
569
+ """
570
+ for row in values:
571
+ for cell in row:
572
+ if _is_sheets_error_token(cell):
573
+ return True
574
+ return False
575
+
576
+
577
+ def _a1_range_for_values(a1_range: str, values: List[List[object]]) -> Optional[str]:
578
+ """
579
+ Compute a tight A1 range for a returned values matrix.
580
+
581
+ This helps keep follow-up includeGridData payloads small vs. using a wide requested range.
582
+ Only applies when the A1 range has an explicit starting cell (e.g., 'Sheet1!B2:D10').
583
+ """
584
+ sheet_name, range_part = _split_sheet_and_range(a1_range)
585
+ if not range_part:
586
+ return None
587
+
588
+ start_part = range_part.split(":", 1)[0]
589
+ try:
590
+ start_col, start_row = _parse_a1_part(start_part)
591
+ except UserInputError:
592
+ return None
593
+ if start_col is None or start_row is None:
594
+ return None
595
+
596
+ height = len(values)
597
+ width = max((len(row) for row in values), default=0)
598
+ if height <= 0 or width <= 0:
599
+ return None
600
+
601
+ end_row = start_row + height - 1
602
+ end_col = start_col + width - 1
603
+
604
+ start_label = f"{_index_to_column(start_col)}{start_row + 1}"
605
+ end_label = f"{_index_to_column(end_col)}{end_row + 1}"
606
+ range_ref = (
607
+ start_label if start_label == end_label else f"{start_label}:{end_label}"
608
+ )
609
+
610
+ if sheet_name:
611
+ return f"{_quote_sheet_title_for_a1(sheet_name)}!{range_ref}"
612
+ return range_ref
613
+
614
+
615
+ def _values_start(a1_range: str) -> Optional[tuple[int, int]]:
616
+ """Return the zero-based (column, row) of an A1 range's first cell, else None."""
617
+ _, range_part = _split_sheet_and_range(a1_range)
618
+ if not range_part:
619
+ return None
620
+ try:
621
+ start_col, start_row = _parse_a1_part(range_part.split(":", 1)[0])
622
+ except UserInputError:
623
+ return None
624
+ # A bare "Totals" is a named range, not column TOTALS.
625
+ if ":" not in range_part and (start_col is None or start_row is None):
626
+ return None
627
+ if start_col is None and start_row is None:
628
+ return None
629
+ return start_col or 0, start_row or 0
630
+
631
+
632
+ _TSV_ESCAPES = str.maketrans({"\\": "\\\\", "\t": "\\t", "\r": "\\r", "\n": "\\n"})
633
+
634
+
635
+ def _format_sheet_values_rows(a1_range: str, values: List[List[object]]) -> str:
636
+ """Render values as lines of sheet row number, then tab-separated cells."""
637
+ start = _values_start(a1_range)
638
+ if start is None:
639
+ start_col, start_row = 0, 0
640
+ legend = "Each line: row number within the range, then tab-separated cells."
641
+ else:
642
+ start_col, start_row = start
643
+ legend = (
644
+ "Each line: sheet row number, then tab-separated cells from column "
645
+ f"{_index_to_column(start_col)}."
646
+ )
647
+
648
+ lines = []
649
+ escaped = False
650
+ for offset, row in enumerate(values):
651
+ cells = ["" if cell is None else str(cell) for cell in row]
652
+ while cells and cells[-1] == "":
653
+ cells.pop()
654
+ escaped_cells = [cell.translate(_TSV_ESCAPES) for cell in cells]
655
+ escaped = escaped or escaped_cells != cells
656
+ lines.append("\t".join([str(start_row + offset + 1), *escaped_cells]))
657
+
658
+ if escaped:
659
+ legend += (
660
+ " Tabs, line breaks and backslashes inside a cell are shown as \\t, "
661
+ "\\n, \\r and \\\\."
662
+ )
663
+ return "\n".join([legend, *lines])
664
+
665
+
666
+ def _a1_range_cell_count(a1_range: str) -> Optional[int]:
667
+ """
668
+ Return cell count for an explicit rectangular A1 range (e.g. A1:C10).
669
+
670
+ Returns None when the range is open-ended or otherwise does not include
671
+ both row and column bounds.
672
+ """
673
+ _, range_part = _split_sheet_and_range(a1_range)
674
+ if not range_part:
675
+ return None
676
+
677
+ if ":" in range_part:
678
+ start_part, end_part = range_part.split(":", 1)
679
+ else:
680
+ start_part = end_part = range_part
681
+
682
+ try:
683
+ start_col, start_row = _parse_a1_part(start_part)
684
+ end_col, end_row = _parse_a1_part(end_part)
685
+ except UserInputError:
686
+ return None
687
+
688
+ if None in (start_col, start_row, end_col, end_row):
689
+ return None
690
+ if end_col < start_col or end_row < start_row:
691
+ return None
692
+
693
+ return (end_col - start_col + 1) * (end_row - start_row + 1)
694
+
695
+
696
+ def _extract_cell_errors_from_grid(spreadsheet: dict) -> list[dict[str, Optional[str]]]:
697
+ """
698
+ Extracts error information from spreadsheet grid data.
699
+
700
+ Iterates through the sheets and their grid data in the provided spreadsheet dictionary,
701
+ collecting all cell errors. Returns a list of dictionaries, each containing:
702
+ - "cell": the A1 notation of the cell with the error,
703
+ - "type": the error type (e.g., "ERROR", "N/A"),
704
+ - "message": the error message, if available.
705
+
706
+ Args:
707
+ spreadsheet (dict): The spreadsheet data as returned by the Sheets API with grid data included.
708
+
709
+ Returns:
710
+ list[dict[str, Optional[str]]]: List of error details for each cell with an error.
711
+ """
712
+ errors: list[dict[str, Optional[str]]] = []
713
+ for sheet in spreadsheet.get("sheets", []) or []:
714
+ sheet_title = sheet.get("properties", {}).get("title") or "Unknown"
715
+ for grid in sheet.get("data", []) or []:
716
+ start_row = _coerce_int(grid.get("startRow"), default=0)
717
+ start_col = _coerce_int(grid.get("startColumn"), default=0)
718
+ for row_offset, row_data in enumerate(grid.get("rowData", []) or []):
719
+ if not row_data:
720
+ continue
721
+ for col_offset, cell_data in enumerate(
722
+ row_data.get("values", []) or []
723
+ ):
724
+ if not cell_data:
725
+ continue
726
+ error_value = (cell_data.get("effectiveValue") or {}).get(
727
+ "errorValue"
728
+ ) or None
729
+ if not error_value:
730
+ continue
731
+ errors.append(
732
+ {
733
+ "cell": _format_a1_cell(
734
+ sheet_title,
735
+ start_row + row_offset,
736
+ start_col + col_offset,
737
+ ),
738
+ "type": error_value.get("type"),
739
+ "message": error_value.get("message"),
740
+ }
741
+ )
742
+ return errors
743
+
744
+
745
+ def _extract_cell_hyperlinks_from_grid(spreadsheet: dict) -> list[dict[str, str]]:
746
+ """
747
+ Extract hyperlink URLs from spreadsheet grid data.
748
+
749
+ Returns a list of dictionaries with:
750
+ - "cell": cell A1 reference
751
+ - "url": hyperlink URL
752
+
753
+ For rich text cells, this includes URLs from both `CellData.hyperlink`
754
+ and `textFormatRuns[].format.link.uri`.
755
+ """
756
+ hyperlinks: list[dict[str, str]] = []
757
+ for sheet in spreadsheet.get("sheets", []) or []:
758
+ sheet_title = sheet.get("properties", {}).get("title") or "Unknown"
759
+ for grid in sheet.get("data", []) or []:
760
+ start_row = _coerce_int(grid.get("startRow"), default=0)
761
+ start_col = _coerce_int(grid.get("startColumn"), default=0)
762
+ for row_offset, row_data in enumerate(grid.get("rowData", []) or []):
763
+ if not row_data:
764
+ continue
765
+ for col_offset, cell_data in enumerate(
766
+ row_data.get("values", []) or []
767
+ ):
768
+ if not cell_data:
769
+ continue
770
+ cell_urls: list[str] = []
771
+ seen_urls: set[str] = set()
772
+
773
+ hyperlink = cell_data.get("hyperlink")
774
+ if (
775
+ isinstance(hyperlink, str)
776
+ and hyperlink
777
+ and hyperlink not in seen_urls
778
+ ):
779
+ seen_urls.add(hyperlink)
780
+ cell_urls.append(hyperlink)
781
+
782
+ for text_run in cell_data.get("textFormatRuns", []) or []:
783
+ if not isinstance(text_run, dict):
784
+ continue
785
+ link_uri = (
786
+ (text_run.get("format") or {}).get("link") or {}
787
+ ).get("uri")
788
+ if not isinstance(link_uri, str) or not link_uri:
789
+ continue
790
+ if link_uri in seen_urls:
791
+ continue
792
+ seen_urls.add(link_uri)
793
+ cell_urls.append(link_uri)
794
+
795
+ if not cell_urls:
796
+ continue
797
+ cell_ref = _format_a1_cell(
798
+ sheet_title, start_row + row_offset, start_col + col_offset
799
+ )
800
+ for url in cell_urls:
801
+ hyperlinks.append({"cell": cell_ref, "url": url})
802
+ return hyperlinks
803
+
804
+
805
+ async def _fetch_detailed_sheet_errors(
806
+ service, spreadsheet_id: str, a1_range: str
807
+ ) -> list[dict[str, Optional[str]]]:
808
+ response = await asyncio.to_thread(
809
+ service.spreadsheets()
810
+ .get(
811
+ spreadsheetId=spreadsheet_id,
812
+ ranges=[a1_range],
813
+ includeGridData=True,
814
+ fields="sheets(properties(title),data(startRow,startColumn,rowData(values(effectiveValue(errorValue(type,message))))))",
815
+ )
816
+ .execute
817
+ )
818
+ return _extract_cell_errors_from_grid(response)
819
+
820
+
821
+ async def _fetch_sheet_hyperlinks(
822
+ service, spreadsheet_id: str, a1_range: str
823
+ ) -> list[dict[str, str]]:
824
+ response = await asyncio.to_thread(
825
+ service.spreadsheets()
826
+ .get(
827
+ spreadsheetId=spreadsheet_id,
828
+ ranges=[a1_range],
829
+ includeGridData=True,
830
+ fields="sheets(properties(title),data(startRow,startColumn,rowData(values(hyperlink,textFormatRuns(format(link(uri)))))))",
831
+ )
832
+ .execute
833
+ )
834
+ return _extract_cell_hyperlinks_from_grid(response)
835
+
836
+
837
+ def _format_sheet_error_section(
838
+ *, errors: list[dict[str, Optional[str]]], range_label: str, max_details: int = 25
839
+ ) -> str:
840
+ """
841
+ Format a list of cell error information into a human-readable section.
842
+
843
+ Args:
844
+ errors: A list of dictionaries, each containing details about a cell error,
845
+ including the cell location, error type, and message.
846
+ range_label: A string label for the range in which the errors occurred.
847
+ max_details: The maximum number of error details to include in the output.
848
+ If the number of errors exceeds this value, the output will be truncated
849
+ and a summary line will indicate how many additional errors were omitted.
850
+
851
+ Returns:
852
+ A formatted string listing the cell errors in a human-readable format.
853
+ If there are no errors, returns an empty string.
854
+ """
855
+ # Limit the number of error details to 25 for performance and readability.
856
+ if not errors:
857
+ return ""
858
+
859
+ lines = []
860
+ for item in errors[:max_details]:
861
+ cell = item.get("cell") or "(unknown cell)"
862
+ error_type = item.get("type")
863
+ message = item.get("message")
864
+ if error_type and message:
865
+ lines.append(f"- {cell}: {error_type} — {message}")
866
+ elif message:
867
+ lines.append(f"- {cell}: {message}")
868
+ elif error_type:
869
+ lines.append(f"- {cell}: {error_type}")
870
+ else:
871
+ lines.append(f"- {cell}: (unknown error)")
872
+
873
+ suffix = (
874
+ f"\n... and {len(errors) - max_details} more errors"
875
+ if len(errors) > max_details
876
+ else ""
877
+ )
878
+ return (
879
+ f"\n\nDetailed cell errors in range '{range_label}':\n"
880
+ + "\n".join(lines)
881
+ + suffix
882
+ )
883
+
884
+
885
+ def _format_sheet_hyperlink_section(
886
+ *, hyperlinks: list[dict[str, str]], range_label: str, max_details: int = 25
887
+ ) -> str:
888
+ """
889
+ Format a list of cell hyperlinks into a human-readable section.
890
+ """
891
+ if not hyperlinks:
892
+ return ""
893
+
894
+ lines = []
895
+ for item in hyperlinks[:max_details]:
896
+ cell = item.get("cell") or "(unknown cell)"
897
+ url = item.get("url") or "(missing url)"
898
+ lines.append(f"- {cell}: {url}")
899
+
900
+ suffix = (
901
+ f"\n... and {len(hyperlinks) - max_details} more hyperlinks"
902
+ if len(hyperlinks) > max_details
903
+ else ""
904
+ )
905
+ return f"\n\nHyperlinks in range '{range_label}':\n" + "\n".join(lines) + suffix
906
+
907
+
908
+ def _color_to_hex(color: Optional[dict]) -> Optional[str]:
909
+ """
910
+ Convert a Sheets color object back to #RRGGBB hex string for display.
911
+ """
912
+ if not color:
913
+ return None
914
+
915
+ def _component(value: Optional[float]) -> int:
916
+ try:
917
+ # Clamp and round to nearest integer in 0-255
918
+ return max(0, min(255, int(round(float(value or 0) * 255))))
919
+ except (TypeError, ValueError):
920
+ return 0
921
+
922
+ red = _component(color.get("red"))
923
+ green = _component(color.get("green"))
924
+ blue = _component(color.get("blue"))
925
+ return f"#{red:02X}{green:02X}{blue:02X}"
926
+
927
+
928
+ def _grid_range_to_a1(grid_range: dict, sheet_titles: dict[int, str]) -> str:
929
+ """
930
+ Convert a GridRange to an A1-like string using known sheet titles.
931
+ Falls back to the sheet ID if the title is unknown.
932
+ """
933
+ sheet_id = grid_range.get("sheetId")
934
+ if sheet_id is None and 0 in sheet_titles:
935
+ sheet_id = 0
936
+ sheet_title = sheet_titles.get(sheet_id, f"Sheet {sheet_id}")
937
+
938
+ start_row = grid_range.get("startRowIndex")
939
+ end_row = grid_range.get("endRowIndex")
940
+ start_col = grid_range.get("startColumnIndex")
941
+ end_col = grid_range.get("endColumnIndex")
942
+
943
+ # If nothing is specified, treat as the whole sheet.
944
+ if start_row is None and end_row is None and start_col is None and end_col is None:
945
+ return sheet_title
946
+
947
+ if end_row is not None and start_row is None:
948
+ start_row = 0
949
+ if end_col is not None and start_col is None:
950
+ start_col = 0
951
+
952
+ def row_label(idx: Optional[int]) -> str:
953
+ return str(idx + 1) if idx is not None else ""
954
+
955
+ def col_label(idx: Optional[int]) -> str:
956
+ return _index_to_column(idx) if idx is not None else ""
957
+
958
+ start_label = f"{col_label(start_col)}{row_label(start_row)}"
959
+ # end indices in GridRange are exclusive; subtract 1 for display
960
+ end_label = f"{col_label(end_col - 1 if end_col is not None else None)}{row_label(end_row - 1 if end_row is not None else None)}"
961
+
962
+ if start_label and end_label:
963
+ # Collapse to a single label only for a bounded single cell (both a
964
+ # column and a row). Column-only (e.g. "A") or row-only (e.g. "1")
965
+ # ranges must keep the "start:end" form to stay valid A1 (A:A, 1:1).
966
+ is_single_cell = start_col is not None and start_row is not None
967
+ range_ref = (
968
+ start_label
969
+ if start_label == end_label and is_single_cell
970
+ else f"{start_label}:{end_label}"
971
+ )
972
+ else:
973
+ range_ref = start_label
974
+
975
+ return f"{sheet_title}!{range_ref}"
976
+
977
+
978
+ def _summarize_conditional_rule(
979
+ rule: dict, index: int, sheet_titles: dict[int, str]
980
+ ) -> str:
981
+ """
982
+ Produce a concise human-readable summary of a conditional formatting rule.
983
+ """
984
+ ranges = rule.get("ranges", [])
985
+ range_labels = [_grid_range_to_a1(rng, sheet_titles) for rng in ranges] or [
986
+ "(no range)"
987
+ ]
988
+
989
+ if "booleanRule" in rule:
990
+ boolean_rule = rule["booleanRule"]
991
+ condition = boolean_rule.get("condition", {})
992
+ cond_type = condition.get("type", "UNKNOWN")
993
+ cond_values = [
994
+ val.get("userEnteredValue")
995
+ for val in condition.get("values", [])
996
+ if isinstance(val, dict) and "userEnteredValue" in val
997
+ ]
998
+ value_desc = f" values={cond_values}" if cond_values else ""
999
+
1000
+ fmt = boolean_rule.get("format", {})
1001
+ fmt_parts = []
1002
+ bg_hex = _color_to_hex(fmt.get("backgroundColor"))
1003
+ if bg_hex:
1004
+ fmt_parts.append(f"bg {bg_hex}")
1005
+ fg_hex = _color_to_hex(fmt.get("textFormat", {}).get("foregroundColor"))
1006
+ if fg_hex:
1007
+ fmt_parts.append(f"text {fg_hex}")
1008
+ fmt_desc = ", ".join(fmt_parts) if fmt_parts else "no format"
1009
+
1010
+ return f"[{index}] {cond_type}{value_desc} -> {fmt_desc} on {', '.join(range_labels)}"
1011
+
1012
+ if "gradientRule" in rule:
1013
+ gradient_rule = rule["gradientRule"]
1014
+ points = []
1015
+ for point_name in ("minpoint", "midpoint", "maxpoint"):
1016
+ point = gradient_rule.get(point_name)
1017
+ if not point:
1018
+ continue
1019
+ color_hex = _color_to_hex(point.get("color"))
1020
+ type_desc = point.get("type", point_name)
1021
+ value_desc = point.get("value")
1022
+ point_desc = type_desc
1023
+ if value_desc:
1024
+ point_desc += f":{value_desc}"
1025
+ if color_hex:
1026
+ point_desc += f" {color_hex}"
1027
+ points.append(point_desc)
1028
+ gradient_desc = " | ".join(points) if points else "gradient"
1029
+ return f"[{index}] gradient -> {gradient_desc} on {', '.join(range_labels)}"
1030
+
1031
+ return f"[{index}] (unknown rule) on {', '.join(range_labels)}"
1032
+
1033
+
1034
+ def _format_conditional_rules_section(
1035
+ sheet_title: str,
1036
+ rules: List[dict],
1037
+ sheet_titles: dict[int, str],
1038
+ indent: str = " ",
1039
+ ) -> str:
1040
+ """
1041
+ Build a multi-line string describing conditional formatting rules for a sheet.
1042
+ """
1043
+ if not rules:
1044
+ return f'{indent}Conditional formats for "{sheet_title}": none.'
1045
+
1046
+ lines = [f'{indent}Conditional formats for "{sheet_title}" ({len(rules)}):']
1047
+ for idx, rule in enumerate(rules):
1048
+ lines.append(
1049
+ f"{indent} {_summarize_conditional_rule(rule, idx, sheet_titles)}"
1050
+ )
1051
+ return "\n".join(lines)
1052
+
1053
+
1054
+ CONDITION_TYPES = {
1055
+ "NUMBER_GREATER",
1056
+ "NUMBER_GREATER_THAN_EQ",
1057
+ "NUMBER_LESS",
1058
+ "NUMBER_LESS_THAN_EQ",
1059
+ "NUMBER_EQ",
1060
+ "NUMBER_NOT_EQ",
1061
+ "TEXT_CONTAINS",
1062
+ "TEXT_NOT_CONTAINS",
1063
+ "TEXT_STARTS_WITH",
1064
+ "TEXT_ENDS_WITH",
1065
+ "TEXT_EQ",
1066
+ "DATE_BEFORE",
1067
+ "DATE_ON_OR_BEFORE",
1068
+ "DATE_AFTER",
1069
+ "DATE_ON_OR_AFTER",
1070
+ "DATE_EQ",
1071
+ "DATE_NOT_EQ",
1072
+ "DATE_BETWEEN",
1073
+ "DATE_NOT_BETWEEN",
1074
+ "NOT_BLANK",
1075
+ "BLANK",
1076
+ "CUSTOM_FORMULA",
1077
+ "ONE_OF_RANGE",
1078
+ }
1079
+
1080
+ GRADIENT_POINT_TYPES = {"MIN", "MAX", "NUMBER", "PERCENT", "PERCENTILE"}
1081
+
1082
+
1083
+ async def _fetch_sheets_with_rules(
1084
+ service, spreadsheet_id: str
1085
+ ) -> tuple[List[dict], dict[int, str]]:
1086
+ """
1087
+ Fetch sheets with titles and conditional format rules in a single request.
1088
+ """
1089
+ response = await asyncio.to_thread(
1090
+ service.spreadsheets()
1091
+ .get(
1092
+ spreadsheetId=spreadsheet_id,
1093
+ fields="sheets(properties(sheetId,title),conditionalFormats)",
1094
+ )
1095
+ .execute
1096
+ )
1097
+ sheets = response.get("sheets", []) or []
1098
+ sheet_titles: dict[int, str] = {}
1099
+ for sheet in sheets:
1100
+ props = sheet.get("properties", {})
1101
+ sid = props.get("sheetId")
1102
+ if sid is not None:
1103
+ sheet_titles[sid] = props.get("title", f"Sheet {sid}")
1104
+ return sheets, sheet_titles
1105
+
1106
+
1107
+ def _select_sheet(sheets: List[dict], sheet_name: Optional[str]) -> dict:
1108
+ """
1109
+ Select a sheet by name, or default to the first sheet if name is not provided.
1110
+ """
1111
+ if not sheets:
1112
+ raise UserInputError("Spreadsheet has no sheets.")
1113
+
1114
+ if sheet_name is None:
1115
+ return sheets[0]
1116
+
1117
+ for sheet in sheets:
1118
+ if sheet.get("properties", {}).get("title") == sheet_name:
1119
+ return sheet
1120
+
1121
+ available_titles = [
1122
+ sheet.get("properties", {}).get("title", "Untitled") for sheet in sheets
1123
+ ]
1124
+ raise UserInputError(
1125
+ f"Sheet '{sheet_name}' not found. Available sheets: {', '.join(available_titles)}."
1126
+ )
1127
+
1128
+
1129
+ async def _copy_paste_range(
1130
+ service,
1131
+ spreadsheet_id: str,
1132
+ source_range: str,
1133
+ destination_range: str,
1134
+ paste_type: str,
1135
+ ) -> str:
1136
+ """Copy source_range onto destination_range with a copyPaste request; return the paste type used."""
1137
+ normalized = paste_type.strip().upper()
1138
+ if normalized not in PASTE_TYPES:
1139
+ raise UserInputError(f"paste_type must be one of {list(PASTE_TYPES)}.")
1140
+
1141
+ metadata = await asyncio.to_thread(
1142
+ service.spreadsheets()
1143
+ .get(
1144
+ spreadsheetId=spreadsheet_id,
1145
+ fields="sheets(properties(sheetId,title,hidden))",
1146
+ )
1147
+ .execute
1148
+ )
1149
+ sheets = sorted(
1150
+ metadata.get("sheets", []),
1151
+ key=lambda sheet: sheet.get("properties", {}).get("hidden", False),
1152
+ )
1153
+ destination = _parse_a1_range(destination_range, sheets)
1154
+ if set(destination) == {"sheetId"}:
1155
+ raise UserInputError("range_name must include a row or column to paste into.")
1156
+ request = {
1157
+ "copyPaste": {
1158
+ "source": _parse_a1_range(source_range, sheets),
1159
+ "destination": destination,
1160
+ "pasteType": normalized,
1161
+ }
1162
+ }
1163
+ await asyncio.to_thread(
1164
+ service.spreadsheets()
1165
+ .batchUpdate(spreadsheetId=spreadsheet_id, body={"requests": [request]})
1166
+ .execute
1167
+ )
1168
+ return normalized
1169
+
1170
+
1171
+ DELIMITED_FILE_DELIMITERS = {".csv": ",", ".tsv": "\t"}
1172
+
1173
+
1174
+ def _read_delimited_file_values(file_path: str) -> List[List[str]]:
1175
+ """Read a local .csv or .tsv file into rows of cell strings."""
1176
+ try:
1177
+ binary = open_validated_file(file_path)
1178
+ except NotARegularFileError as exc:
1179
+ raise UserInputError(f"file_path is not a file: {file_path}") from exc
1180
+ with io.TextIOWrapper(binary, encoding="utf-8-sig", newline="") as handle:
1181
+ delimiter = DELIMITED_FILE_DELIMITERS.get(Path(handle.name).suffix.lower())
1182
+ if delimiter is None:
1183
+ raise UserInputError(
1184
+ "file_path must be a .csv or .tsv file; convert other formats with "
1185
+ "import_to_google_sheets."
1186
+ )
1187
+ try:
1188
+ rows = list(csv.reader(handle, delimiter=delimiter, strict=True))
1189
+ except UnicodeDecodeError as exc:
1190
+ raise UserInputError(f"file_path must be UTF-8 text: {exc}") from exc
1191
+ except csv.Error as exc:
1192
+ raise UserInputError(
1193
+ f"Could not parse file_path as delimited text: {exc}"
1194
+ ) from exc
1195
+ if not any(rows):
1196
+ raise UserInputError(f"file_path has no rows to write: {file_path}")
1197
+ return rows
1198
+
1199
+
1200
+ async def _copy_sheet_to_spreadsheet(
1201
+ service,
1202
+ spreadsheet_id: str,
1203
+ sheet_id: int,
1204
+ destination_spreadsheet_id: str,
1205
+ sheet_name: Optional[str],
1206
+ insert_sheet_index: Optional[int],
1207
+ ) -> dict:
1208
+ """Copy a sheet into another spreadsheet with an optional title and index; return its properties."""
1209
+ new_props = await asyncio.to_thread(
1210
+ service.spreadsheets()
1211
+ .sheets()
1212
+ .copyTo(
1213
+ spreadsheetId=spreadsheet_id,
1214
+ sheetId=sheet_id,
1215
+ body={"destinationSpreadsheetId": destination_spreadsheet_id},
1216
+ )
1217
+ .execute
1218
+ )
1219
+
1220
+ updates: dict[str, Any] = {}
1221
+ if sheet_name is not None:
1222
+ updates["title"] = sheet_name
1223
+ if insert_sheet_index is not None:
1224
+ updates["index"] = insert_sheet_index
1225
+ if not updates:
1226
+ return new_props
1227
+
1228
+ new_id = new_props["sheetId"]
1229
+ update_request = {
1230
+ "updateSheetProperties": {
1231
+ "properties": {"sheetId": new_id, **updates},
1232
+ "fields": ",".join(updates),
1233
+ }
1234
+ }
1235
+ try:
1236
+ await asyncio.to_thread(
1237
+ service.spreadsheets()
1238
+ .batchUpdate(
1239
+ spreadsheetId=destination_spreadsheet_id,
1240
+ body={"requests": [update_request]},
1241
+ )
1242
+ .execute
1243
+ )
1244
+ except Exception:
1245
+ try:
1246
+ await asyncio.to_thread(
1247
+ service.spreadsheets()
1248
+ .batchUpdate(
1249
+ spreadsheetId=destination_spreadsheet_id,
1250
+ body={"requests": [{"deleteSheet": {"sheetId": new_id}}]},
1251
+ )
1252
+ .execute
1253
+ )
1254
+ except Exception as cleanup_error:
1255
+ raise RuntimeError(
1256
+ f"Copied sheet '{new_props['title']}' (ID: {new_id}) to spreadsheet "
1257
+ f"{destination_spreadsheet_id} but could not set its title or index; "
1258
+ "delete or rename it before retrying."
1259
+ ) from cleanup_error
1260
+ raise
1261
+ return {**new_props, **updates}
1262
+
1263
+
1264
+ def _parse_condition_values(
1265
+ condition_values: Optional[Union[str, List[Union[str, int, float]]]],
1266
+ ) -> Optional[List[Union[str, int, float]]]:
1267
+ """
1268
+ Normalize and validate condition_values into a list of strings/numbers.
1269
+ """
1270
+ parsed = condition_values
1271
+ if isinstance(parsed, str):
1272
+ try:
1273
+ parsed = json.loads(parsed)
1274
+ except json.JSONDecodeError as exc:
1275
+ raise UserInputError(
1276
+ "condition_values must be a list or a JSON-encoded list (e.g., '[\"=$B2>1000\"]')."
1277
+ ) from exc
1278
+
1279
+ if parsed is not None and not isinstance(parsed, list):
1280
+ parsed = [parsed]
1281
+
1282
+ if parsed:
1283
+ for idx, val in enumerate(parsed):
1284
+ if not isinstance(val, (str, int, float)):
1285
+ raise UserInputError(
1286
+ f"condition_values[{idx}] must be a string or number, got {type(val).__name__}."
1287
+ )
1288
+
1289
+ return parsed
1290
+
1291
+
1292
+ def _parse_gradient_points(
1293
+ gradient_points: Optional[Union[str, List[dict]]],
1294
+ ) -> Optional[List[dict]]:
1295
+ """
1296
+ Normalize gradient points into a list of dicts with type/value/color.
1297
+ Each point must have a 'type' (MIN, MAX, NUMBER, PERCENT, PERCENTILE) and a color.
1298
+ """
1299
+ if gradient_points is None:
1300
+ return None
1301
+
1302
+ parsed = gradient_points
1303
+ if isinstance(parsed, str):
1304
+ try:
1305
+ parsed = json.loads(parsed)
1306
+ except json.JSONDecodeError as exc:
1307
+ raise UserInputError(
1308
+ "gradient_points must be a list or JSON-encoded list of points "
1309
+ '(e.g., \'[{"type":"MIN","color":"#ffffff"}, {"type":"MAX","color":"#ff0000"}]\').'
1310
+ ) from exc
1311
+
1312
+ if not isinstance(parsed, list):
1313
+ raise UserInputError("gradient_points must be a list of point objects.")
1314
+
1315
+ if len(parsed) < 2 or len(parsed) > 3:
1316
+ raise UserInputError("Provide 2 or 3 gradient points (min/max or min/mid/max).")
1317
+
1318
+ normalized_points: List[dict] = []
1319
+ for idx, point in enumerate(parsed):
1320
+ if not isinstance(point, dict):
1321
+ raise UserInputError(
1322
+ f"gradient_points[{idx}] must be an object with type/color."
1323
+ )
1324
+
1325
+ point_type = point.get("type")
1326
+ if not point_type or point_type.upper() not in GRADIENT_POINT_TYPES:
1327
+ raise UserInputError(
1328
+ f"gradient_points[{idx}].type must be one of {sorted(GRADIENT_POINT_TYPES)}."
1329
+ )
1330
+ color_raw = point.get("color")
1331
+ color_dict = (
1332
+ _parse_hex_color(color_raw)
1333
+ if not isinstance(color_raw, dict)
1334
+ else color_raw
1335
+ )
1336
+ if not color_dict:
1337
+ raise UserInputError(f"gradient_points[{idx}].color is required.")
1338
+
1339
+ normalized = {"type": point_type.upper(), "color": color_dict}
1340
+ if "value" in point and point["value"] is not None:
1341
+ normalized["value"] = str(point["value"])
1342
+ normalized_points.append(normalized)
1343
+
1344
+ return normalized_points
1345
+
1346
+
1347
+ def _build_boolean_rule(
1348
+ ranges: List[dict],
1349
+ condition_type: str,
1350
+ condition_values: Optional[List[Union[str, int, float]]],
1351
+ background_color: Optional[str],
1352
+ text_color: Optional[str],
1353
+ ) -> tuple[dict, str]:
1354
+ """
1355
+ Build a Sheets boolean conditional formatting rule payload.
1356
+ Returns the rule and the normalized condition type.
1357
+ """
1358
+ if not background_color and not text_color:
1359
+ raise UserInputError(
1360
+ "Provide at least one of background_color or text_color for the rule format."
1361
+ )
1362
+
1363
+ cond_type_normalized = condition_type.upper()
1364
+ if cond_type_normalized not in CONDITION_TYPES:
1365
+ raise UserInputError(
1366
+ f"condition_type must be one of {sorted(CONDITION_TYPES)}."
1367
+ )
1368
+
1369
+ condition = {"type": cond_type_normalized}
1370
+ if condition_values:
1371
+ condition["values"] = [
1372
+ {"userEnteredValue": str(value)} for value in condition_values
1373
+ ]
1374
+
1375
+ bg_color_parsed = _parse_hex_color(background_color)
1376
+ text_color_parsed = _parse_hex_color(text_color)
1377
+
1378
+ format_obj = {}
1379
+ if bg_color_parsed:
1380
+ format_obj["backgroundColor"] = bg_color_parsed
1381
+ if text_color_parsed:
1382
+ format_obj["textFormat"] = {"foregroundColor": text_color_parsed}
1383
+
1384
+ return (
1385
+ {
1386
+ "ranges": ranges,
1387
+ "booleanRule": {
1388
+ "condition": condition,
1389
+ "format": format_obj,
1390
+ },
1391
+ },
1392
+ cond_type_normalized,
1393
+ )
1394
+
1395
+
1396
+ def _build_gradient_rule(
1397
+ ranges: List[dict],
1398
+ gradient_points: List[dict],
1399
+ ) -> dict:
1400
+ """
1401
+ Build a Sheets gradient conditional formatting rule payload.
1402
+ """
1403
+ rule_body: dict = {"ranges": ranges, "gradientRule": {}}
1404
+ if len(gradient_points) == 2:
1405
+ rule_body["gradientRule"]["minpoint"] = gradient_points[0]
1406
+ rule_body["gradientRule"]["maxpoint"] = gradient_points[1]
1407
+ else:
1408
+ rule_body["gradientRule"]["minpoint"] = gradient_points[0]
1409
+ rule_body["gradientRule"]["midpoint"] = gradient_points[1]
1410
+ rule_body["gradientRule"]["maxpoint"] = gradient_points[2]
1411
+ return rule_body
1412
+
1413
+
1414
+ def _extract_cell_notes_from_grid(spreadsheet: dict) -> list[dict[str, str]]:
1415
+ """
1416
+ Extract cell notes from spreadsheet grid data.
1417
+
1418
+ Returns a list of dictionaries with:
1419
+ - "cell": cell A1 reference
1420
+ - "note": the note text
1421
+ """
1422
+ notes: list[dict[str, str]] = []
1423
+ for sheet in spreadsheet.get("sheets", []) or []:
1424
+ sheet_title = sheet.get("properties", {}).get("title") or "Unknown"
1425
+ for grid in sheet.get("data", []) or []:
1426
+ start_row = _coerce_int(grid.get("startRow"), default=0)
1427
+ start_col = _coerce_int(grid.get("startColumn"), default=0)
1428
+ for row_offset, row_data in enumerate(grid.get("rowData", []) or []):
1429
+ if not row_data:
1430
+ continue
1431
+ for col_offset, cell_data in enumerate(
1432
+ row_data.get("values", []) or []
1433
+ ):
1434
+ if not cell_data:
1435
+ continue
1436
+ note = cell_data.get("note")
1437
+ if not note:
1438
+ continue
1439
+ notes.append(
1440
+ {
1441
+ "cell": _format_a1_cell(
1442
+ sheet_title,
1443
+ start_row + row_offset,
1444
+ start_col + col_offset,
1445
+ ),
1446
+ "note": note,
1447
+ }
1448
+ )
1449
+ return notes
1450
+
1451
+
1452
+ async def _fetch_sheet_notes(
1453
+ service, spreadsheet_id: str, a1_range: str
1454
+ ) -> list[dict[str, str]]:
1455
+ """Fetch cell notes for the given range via spreadsheets.get with includeGridData."""
1456
+ response = await asyncio.to_thread(
1457
+ service.spreadsheets()
1458
+ .get(
1459
+ spreadsheetId=spreadsheet_id,
1460
+ ranges=[a1_range],
1461
+ includeGridData=True,
1462
+ fields="sheets(properties(title),data(startRow,startColumn,rowData(values(note))))",
1463
+ )
1464
+ .execute
1465
+ )
1466
+ return _extract_cell_notes_from_grid(response)
1467
+
1468
+
1469
+ def _format_sheet_notes_section(
1470
+ *, notes: list[dict[str, str]], range_label: str, max_details: int = 25
1471
+ ) -> str:
1472
+ """
1473
+ Format a list of cell notes into a human-readable section.
1474
+ """
1475
+ if not notes:
1476
+ return ""
1477
+
1478
+ lines = []
1479
+ for item in notes[:max_details]:
1480
+ cell = item.get("cell") or "(unknown cell)"
1481
+ note = item.get("note") or "(empty note)"
1482
+ lines.append(f"- {cell}: {note}")
1483
+
1484
+ suffix = (
1485
+ f"\n... and {len(notes) - max_details} more notes"
1486
+ if len(notes) > max_details
1487
+ else ""
1488
+ )
1489
+ return f"\n\nCell notes in range '{range_label}':\n" + "\n".join(lines) + suffix
1490
+
1491
+
1492
+ def _describe_data_validation(rule: dict[str, Any]) -> str:
1493
+ """Describe a DataValidationRule as e.g. 'ONE_OF_LIST: "Yes", "No" (strict)'."""
1494
+ condition = rule.get("condition") or {}
1495
+ text = condition.get("type") or "UNKNOWN"
1496
+ values = [
1497
+ json.dumps(
1498
+ str(value.get("userEnteredValue") or value.get("relativeDate") or ""),
1499
+ ensure_ascii=False,
1500
+ )
1501
+ for value in condition.get("values") or []
1502
+ ]
1503
+ if values:
1504
+ text += ": " + ", ".join(values)
1505
+ if rule.get("strict"):
1506
+ text += " (strict)"
1507
+ if rule.get("inputMessage"):
1508
+ text += f" (help: {json.dumps(rule['inputMessage'], ensure_ascii=False)})"
1509
+ return text
1510
+
1511
+
1512
+ def _extract_cell_validation_from_grid(
1513
+ spreadsheet: dict[str, Any],
1514
+ ) -> list[dict[str, str]]:
1515
+ """Return {"range", "rule"} entries, merging a rule's consecutive rows in a column."""
1516
+ runs: list[dict[str, Any]] = []
1517
+ open_runs: dict[tuple[str, int, str], dict[str, Any]] = {}
1518
+ for sheet in spreadsheet.get("sheets", []) or []:
1519
+ sheet_title = sheet.get("properties", {}).get("title") or "Unknown"
1520
+ for grid in sheet.get("data", []) or []:
1521
+ start_row = _coerce_int(grid.get("startRow"), default=0)
1522
+ start_col = _coerce_int(grid.get("startColumn"), default=0)
1523
+ for row_offset, row_data in enumerate(grid.get("rowData", []) or []):
1524
+ for col_offset, cell_data in enumerate(
1525
+ (row_data or {}).get("values", []) or []
1526
+ ):
1527
+ rule = (cell_data or {}).get("dataValidation")
1528
+ if not rule:
1529
+ continue
1530
+ row = start_row + row_offset
1531
+ col = start_col + col_offset
1532
+ key = (sheet_title, col, json.dumps(rule, sort_keys=True))
1533
+ run = open_runs.get(key)
1534
+ if run and run["end_row"] == row - 1:
1535
+ run["end_row"] = row
1536
+ continue
1537
+ run = {
1538
+ "sheet": sheet_title,
1539
+ "col": col,
1540
+ "rule": _describe_data_validation(rule),
1541
+ "start_row": row,
1542
+ "end_row": row,
1543
+ }
1544
+ open_runs[key] = run
1545
+ runs.append(run)
1546
+
1547
+ rules: list[dict[str, str]] = []
1548
+ for run in runs:
1549
+ cell_range = _format_a1_cell(run["sheet"], run["start_row"], run["col"])
1550
+ if run["end_row"] != run["start_row"]:
1551
+ cell_range += f":{_index_to_column(run['col'])}{run['end_row'] + 1}"
1552
+ rules.append({"range": cell_range, "rule": run["rule"]})
1553
+ return rules
1554
+
1555
+
1556
+ def _format_sheet_validation_section(
1557
+ *, rules: list[dict[str, str]], range_label: str, max_details: int = 25
1558
+ ) -> str:
1559
+ """Format data validation rules into a human-readable section."""
1560
+ if not rules:
1561
+ return ""
1562
+
1563
+ lines = [f"- {item['range']}: {item['rule']}" for item in rules[:max_details]]
1564
+ suffix = (
1565
+ f"\n... and {len(rules) - max_details} more validation ranges"
1566
+ if len(rules) > max_details
1567
+ else ""
1568
+ )
1569
+ return (
1570
+ f"\n\nData validation in range '{range_label}':\n" + "\n".join(lines) + suffix
1571
+ )
1572
+
1573
+
1574
+ async def _fetch_validation_section(
1575
+ service: Any,
1576
+ spreadsheet_id: str,
1577
+ requested_range: str,
1578
+ values: List[List[object]],
1579
+ ) -> str:
1580
+ """Fetch data validation rules as a formatted section.
1581
+
1582
+ Reads the requested range, since validation often sits on blank cells that
1583
+ ``values.get`` leaves out, and falls back to the populated range when the
1584
+ requested one is open-ended or over the cell cap.
1585
+ """
1586
+ target = requested_range
1587
+ cell_count = _a1_range_cell_count(target)
1588
+ if cell_count is None or cell_count > MAX_GRID_METADATA_CELLS:
1589
+ target = _a1_range_for_values(requested_range, values)
1590
+ cell_count = _a1_range_cell_count(target) if target else None
1591
+ if cell_count is None or cell_count > MAX_GRID_METADATA_CELLS:
1592
+ return (
1593
+ f"\n\nData validation was not read for range '{requested_range}': "
1594
+ f"pass a range of at most {MAX_GRID_METADATA_CELLS} cells."
1595
+ )
1596
+
1597
+ try:
1598
+ response = await asyncio.to_thread(
1599
+ service.spreadsheets()
1600
+ .get(
1601
+ spreadsheetId=spreadsheet_id,
1602
+ ranges=[target],
1603
+ includeGridData=True,
1604
+ fields=(
1605
+ "sheets(properties(title),data(startRow,startColumn,"
1606
+ "rowData(values(dataValidation))))"
1607
+ ),
1608
+ )
1609
+ .execute
1610
+ )
1611
+ except Exception as exc:
1612
+ logger.warning(
1613
+ "[read_sheet_values] Failed fetching data validation for range '%s': %s",
1614
+ target,
1615
+ exc,
1616
+ )
1617
+ return f"\n\nData validation could not be read for range '{target}'."
1618
+
1619
+ return _format_sheet_validation_section(
1620
+ rules=_extract_cell_validation_from_grid(response), range_label=target
1621
+ )
1622
+
1623
+
1624
+ async def _fetch_cell_formulas(
1625
+ service,
1626
+ spreadsheet_id: str,
1627
+ resolved_range: str,
1628
+ ) -> tuple[str, List[List[object]]]:
1629
+ """Fetch formula strings for cells in the given range.
1630
+
1631
+ Makes a second values().get() call with valueRenderOption="FORMULA" and
1632
+ returns a formatted section listing any cells whose value starts with "=".
1633
+ Cells containing plain values are silently skipped.
1634
+
1635
+ Returns an empty section and empty values list if the request fails.
1636
+ """
1637
+ try:
1638
+ result = await asyncio.to_thread(
1639
+ service.spreadsheets()
1640
+ .values()
1641
+ .get(
1642
+ spreadsheetId=spreadsheet_id,
1643
+ range=resolved_range,
1644
+ valueRenderOption="FORMULA",
1645
+ )
1646
+ .execute
1647
+ )
1648
+ except Exception as exc:
1649
+ logger.warning(
1650
+ "[read_sheet_values] Failed fetching formula values for range '%s': %s",
1651
+ resolved_range,
1652
+ exc,
1653
+ )
1654
+ return "", []
1655
+
1656
+ formula_values = result.get("values", [])
1657
+ formulas: list[dict[str, str]] = []
1658
+
1659
+ sheet_name, range_part = _split_sheet_and_range(resolved_range)
1660
+ start_part = range_part.split(":")[0] if ":" in range_part else range_part
1661
+ start_col_idx, start_row_idx = _parse_a1_part(start_part)
1662
+ base_col = start_col_idx if start_col_idx is not None else 0
1663
+ base_row = start_row_idx if start_row_idx is not None else 0
1664
+
1665
+ for row_offset, formula_row in enumerate(formula_values):
1666
+ for col_offset, cell_value in enumerate(formula_row):
1667
+ if isinstance(cell_value, str) and cell_value.startswith("="):
1668
+ abs_col = base_col + col_offset
1669
+ abs_row = base_row + row_offset
1670
+ cell_ref = f"{_index_to_column(abs_col)}{abs_row + 1}"
1671
+ if sheet_name:
1672
+ cell_ref = f"{_quote_sheet_title_for_a1(sheet_name)}!{cell_ref}"
1673
+ formulas.append({"cell": cell_ref, "formula": cell_value})
1674
+
1675
+ return (
1676
+ _format_sheet_formula_section(formulas=formulas, range_label=resolved_range),
1677
+ formula_values,
1678
+ )
1679
+
1680
+
1681
+ def _format_sheet_formula_section(
1682
+ *, formulas: list[dict[str, str]], range_label: str, max_details: int = 50
1683
+ ) -> str:
1684
+ """Format a list of formula cells into a human-readable section."""
1685
+ if not formulas:
1686
+ return ""
1687
+
1688
+ lines = []
1689
+ for item in formulas[:max_details]:
1690
+ cell = item.get("cell") or "(unknown cell)"
1691
+ formula = item.get("formula") or "(empty formula)"
1692
+ lines.append(f"- {cell}: {formula}")
1693
+
1694
+ suffix = (
1695
+ f"\n... and {len(formulas) - max_details} more formula cells"
1696
+ if len(formulas) > max_details
1697
+ else ""
1698
+ )
1699
+ return f"\n\nFormula cells in range '{range_label}':\n" + "\n".join(lines) + suffix
1700
+
1701
+
1702
+ async def _fetch_grid_metadata(
1703
+ service,
1704
+ spreadsheet_id: str,
1705
+ resolved_range: str,
1706
+ values: List[List[object]],
1707
+ include_hyperlinks: bool = False,
1708
+ include_notes: bool = False,
1709
+ include_smart_chips: bool = False,
1710
+ ) -> tuple[str, str, str]:
1711
+ """Fetch hyperlinks, notes, and/or smart chips for a range via a single spreadsheets.get call.
1712
+
1713
+ Computes tight range bounds, enforces the cell-count cap, builds a combined
1714
+ ``fields`` selector so only one API round-trip is needed when multiple flags are
1715
+ ``True``, then parses the response into formatted output sections.
1716
+
1717
+ Returns:
1718
+ (hyperlink_section, notes_section, smart_chips_section) — each is an empty string when the
1719
+ corresponding flag is ``False`` or no data was found.
1720
+ """
1721
+ if not include_hyperlinks and not include_notes and not include_smart_chips:
1722
+ return "", "", ""
1723
+
1724
+ tight_range = _a1_range_for_values(resolved_range, values)
1725
+ if not tight_range:
1726
+ logger.info(
1727
+ "[read_sheet_values] Skipping grid metadata fetch for range '%s': "
1728
+ "unable to determine tight bounds",
1729
+ resolved_range,
1730
+ )
1731
+ return "", "", ""
1732
+
1733
+ cell_count = _a1_range_cell_count(tight_range) or sum(len(row) for row in values)
1734
+ if cell_count > MAX_GRID_METADATA_CELLS:
1735
+ logger.info(
1736
+ "[read_sheet_values] Skipping grid metadata fetch for large range "
1737
+ "'%s' (%d cells > %d limit)",
1738
+ tight_range,
1739
+ cell_count,
1740
+ MAX_GRID_METADATA_CELLS,
1741
+ )
1742
+ return "", "", ""
1743
+
1744
+ # Build a combined fields selector so we hit the API at most once.
1745
+ value_fields: list[str] = []
1746
+ if include_hyperlinks:
1747
+ value_fields.extend(["hyperlink", "textFormatRuns(format(link(uri)))"])
1748
+ if include_notes:
1749
+ value_fields.append("note")
1750
+ if include_smart_chips:
1751
+ value_fields.append("chipRuns")
1752
+
1753
+ fields = (
1754
+ "sheets(properties(title),data(startRow,startColumn,"
1755
+ f"rowData(values({','.join(value_fields)}))))"
1756
+ )
1757
+
1758
+ try:
1759
+ response = await asyncio.to_thread(
1760
+ service.spreadsheets()
1761
+ .get(
1762
+ spreadsheetId=spreadsheet_id,
1763
+ ranges=[tight_range],
1764
+ includeGridData=True,
1765
+ fields=fields,
1766
+ )
1767
+ .execute
1768
+ )
1769
+ except Exception as exc:
1770
+ logger.warning(
1771
+ "[read_sheet_values] Failed fetching grid metadata for range '%s': %s",
1772
+ tight_range,
1773
+ exc,
1774
+ )
1775
+ return "", "", ""
1776
+
1777
+ hyperlink_section = ""
1778
+ if include_hyperlinks:
1779
+ hyperlinks = _extract_cell_hyperlinks_from_grid(response)
1780
+ hyperlink_section = _format_sheet_hyperlink_section(
1781
+ hyperlinks=hyperlinks, range_label=tight_range
1782
+ )
1783
+
1784
+ notes_section = ""
1785
+ if include_notes:
1786
+ notes = _extract_cell_notes_from_grid(response)
1787
+ notes_section = _format_sheet_notes_section(
1788
+ notes=notes, range_label=tight_range
1789
+ )
1790
+
1791
+ smart_chips_section = ""
1792
+ if include_smart_chips:
1793
+ smart_chips = _extract_cell_smart_chips_from_grid(response)
1794
+ smart_chips_section = _format_sheet_smart_chips_section(
1795
+ smart_chips=smart_chips, range_label=tight_range
1796
+ )
1797
+
1798
+ return hyperlink_section, notes_section, smart_chips_section
1799
+
1800
+
1801
+ def _extract_cell_smart_chips_from_grid(spreadsheet: dict) -> list[dict[str, str]]:
1802
+ """
1803
+ Extract Drive and People smart chips from spreadsheet grid data.
1804
+
1805
+ Returns a list of dictionaries with:
1806
+ - "cell": cell A1 reference
1807
+ - "type": "drive" | "person"
1808
+ - "value": Drive link URI or person email
1809
+ """
1810
+ smart_chips: list[dict[str, str]] = []
1811
+ for sheet in spreadsheet.get("sheets", []) or []:
1812
+ sheet_title = sheet.get("properties", {}).get("title") or "Unknown"
1813
+ for grid in sheet.get("data", []) or []:
1814
+ start_row = _coerce_int(grid.get("startRow"), default=0)
1815
+ start_col = _coerce_int(grid.get("startColumn"), default=0)
1816
+ for row_offset, row_data in enumerate(grid.get("rowData", []) or []):
1817
+ if not row_data:
1818
+ continue
1819
+ for col_offset, cell_data in enumerate(
1820
+ row_data.get("values", []) or []
1821
+ ):
1822
+ if not cell_data:
1823
+ continue
1824
+ for chip_run in cell_data.get("chipRuns") or []:
1825
+ # Reads also return plain-text runs, which carry an empty chip.
1826
+ chip = chip_run.get("chip") or {}
1827
+ if "richLinkProperties" in chip:
1828
+ chip_type = "drive"
1829
+ value = chip["richLinkProperties"].get("uri")
1830
+ elif "personProperties" in chip:
1831
+ chip_type = "person"
1832
+ value = chip["personProperties"].get("email")
1833
+ else:
1834
+ continue
1835
+ smart_chips.append(
1836
+ {
1837
+ "cell": _format_a1_cell(
1838
+ sheet_title,
1839
+ start_row + row_offset,
1840
+ start_col + col_offset,
1841
+ ),
1842
+ "type": chip_type,
1843
+ "value": value or "",
1844
+ }
1845
+ )
1846
+ return smart_chips
1847
+
1848
+
1849
+ def _format_sheet_smart_chips_section(
1850
+ *, smart_chips: list[dict[str, str]], range_label: str, max_details: int = 25
1851
+ ) -> str:
1852
+ """Format a list of smart chips into a human-readable section."""
1853
+ if not smart_chips:
1854
+ return ""
1855
+
1856
+ labels = {"drive": "Drive Chip", "person": "Person Chip"}
1857
+ lines = [
1858
+ f"- {item['cell']}: [{labels[item['type']]}] {item['value']}"
1859
+ for item in smart_chips[:max_details]
1860
+ ]
1861
+ suffix = (
1862
+ f"\n... and {len(smart_chips) - max_details} more smart chips"
1863
+ if len(smart_chips) > max_details
1864
+ else ""
1865
+ )
1866
+ return f"\n\nSmart Chips in range '{range_label}':\n" + "\n".join(lines) + suffix
1867
+
1868
+
1869
+ def _parse_single_chip_properties(
1870
+ item: Any, default_type: Optional[str] = None
1871
+ ) -> tuple[str, dict]:
1872
+ """Parse a single chip item (str or dict) into (chip_type, chip_properties)."""
1873
+ if item is None or item == "":
1874
+ raise UserInputError("Empty chip item cannot be parsed.")
1875
+
1876
+ chip_type = default_type.lower() if default_type else None
1877
+ uri = None
1878
+ email = None
1879
+
1880
+ if isinstance(item, dict):
1881
+ if "type" in item:
1882
+ chip_type = str(item["type"]).lower()
1883
+ uri = item.get("uri") or item.get("url")
1884
+ email = item.get("email")
1885
+ if not uri and not email:
1886
+ if "folder_id" in item:
1887
+ uri = f"https://drive.google.com/drive/folders/{item['folder_id']}"
1888
+ chip_type = "drive"
1889
+ elif "file_id" in item:
1890
+ uri = f"https://drive.google.com/file/d/{item['file_id']}/view"
1891
+ chip_type = "drive"
1892
+ elif "id" in item:
1893
+ uri = f"https://drive.google.com/open?id={item['id']}"
1894
+ chip_type = "drive"
1895
+ elif isinstance(item, str):
1896
+ val = item.strip()
1897
+ if not chip_type:
1898
+ if val.startswith(("http://", "https://")) or "drive.google.com" in val:
1899
+ chip_type = "drive"
1900
+ uri = val
1901
+ elif "@" in val and not val.startswith("http"):
1902
+ chip_type = "person"
1903
+ email = val.replace("mailto:", "").strip()
1904
+ elif len(val) >= 20 and re.match(r"^[A-Za-z0-9_-]+$", val):
1905
+ chip_type = "drive"
1906
+ uri = f"https://drive.google.com/open?id={val}"
1907
+ else:
1908
+ raise UserInputError(
1909
+ f"Cannot infer chip type from '{val}'. Pass a Drive URL or ID, "
1910
+ "an email address, or set chip_type explicitly."
1911
+ )
1912
+ elif chip_type == "drive":
1913
+ if val.startswith(("http://", "https://")):
1914
+ uri = val
1915
+ else:
1916
+ uri = f"https://drive.google.com/open?id={val}"
1917
+ elif chip_type == "person":
1918
+ email = val.replace("mailto:", "").strip()
1919
+ else:
1920
+ raise UserInputError(
1921
+ f"Unsupported chip item type: {type(item).__name__} ({item})"
1922
+ )
1923
+
1924
+ if chip_type == "drive":
1925
+ if not uri:
1926
+ raise UserInputError(
1927
+ f"Drive chip requires a URI or file/folder ID, got: {item}"
1928
+ )
1929
+ return "drive", {"richLinkProperties": {"uri": uri}}
1930
+ elif chip_type == "person":
1931
+ if not email:
1932
+ raise UserInputError(f"Person chip requires an email address, got: {item}")
1933
+ return "person", {"personProperties": {"email": email}}
1934
+ else:
1935
+ raise UserInputError(
1936
+ f"Unknown chip_type '{chip_type}'. Supported types: 'drive', 'person'."
1937
+ )
1938
+
1939
+
1940
+ def _create_chip_cell_data(
1941
+ item: Any, default_type: Optional[str] = None
1942
+ ) -> Optional[dict]:
1943
+ """Construct a CellData dictionary containing smart chip(s) for Sheets API.
1944
+
1945
+ Args:
1946
+ item: A single chip (str or dict), or a list of chips for a single cell.
1947
+ default_type: Optional default chip type ("drive" or "person").
1948
+
1949
+ Returns:
1950
+ A CellData dictionary with userEnteredValue and chipRuns, or None if item is empty.
1951
+ """
1952
+ if item is None or item == "" or item == []:
1953
+ return None
1954
+
1955
+ # Multi-chips in a single cell: list or tuple of chip items
1956
+ if isinstance(item, (list, tuple)):
1957
+ active_items = [x for x in item if x is not None and x != ""]
1958
+ if not active_items:
1959
+ return None
1960
+ chip_runs = []
1961
+ for idx, sub_item in enumerate(active_items):
1962
+ _, chip_props = _parse_single_chip_properties(sub_item, default_type)
1963
+ chip_runs.append(
1964
+ {
1965
+ "startIndex": idx * 2,
1966
+ "chip": chip_props,
1967
+ }
1968
+ )
1969
+ return {
1970
+ "userEnteredValue": {"stringValue": " ".join(["@"] * len(active_items))},
1971
+ "chipRuns": chip_runs,
1972
+ }
1973
+
1974
+ _, chip_props = _parse_single_chip_properties(item, default_type)
1975
+ return {
1976
+ "userEnteredValue": {"stringValue": "@"},
1977
+ "chipRuns": [
1978
+ {
1979
+ "startIndex": 0,
1980
+ "chip": chip_props,
1981
+ }
1982
+ ],
1983
+ }
1984
+
1985
+
1986
+ def _normalize_chips_input(
1987
+ chips: Any,
1988
+ start_row: Optional[int],
1989
+ end_row: Optional[int],
1990
+ start_col: Optional[int],
1991
+ end_col: Optional[int],
1992
+ default_chip_type: Optional[str] = None,
1993
+ ) -> list[tuple[int, int, dict]]:
1994
+ """Parse input chips and map each chip to its (row_idx, col_idx, cell_data).
1995
+
1996
+ Args:
1997
+ chips: Raw chips parameter (string, list, list of lists, dict).
1998
+ start_row: Zero-based start row index.
1999
+ end_row: Zero-based end row index (inclusive).
2000
+ start_col: Zero-based start column index.
2001
+ end_col: Zero-based end column index (inclusive).
2002
+ default_chip_type: Optional chip type override ("drive", "person").
2003
+
2004
+ Returns:
2005
+ List of (row_idx, col_idx, cell_data) tuples.
2006
+ """
2007
+ if isinstance(chips, str):
2008
+ try:
2009
+ parsed = json.loads(chips)
2010
+ if isinstance(parsed, (list, dict, str)):
2011
+ chips = parsed
2012
+ except (json.JSONDecodeError, ValueError):
2013
+ pass
2014
+
2015
+ start_r = start_row if start_row is not None else 0
2016
+ start_c = start_col if start_col is not None else 0
2017
+
2018
+ updates: list[tuple[int, int, dict]] = []
2019
+
2020
+ is_single_row = (
2021
+ start_row is not None and end_row is not None and start_row == end_row
2022
+ )
2023
+ is_single_col = (
2024
+ start_col is not None and end_col is not None and start_col == end_col
2025
+ )
2026
+ is_single_cell = is_single_row and is_single_col
2027
+
2028
+ # Case 1: Single cell target (e.g. F3 or F3:F3)
2029
+ # Any chips provided (single item, list of chips, or nested list [[c1, c2]]) go into this single cell
2030
+ if is_single_cell:
2031
+ if isinstance(chips, list) and len(chips) == 1 and isinstance(chips[0], list):
2032
+ chips = chips[0]
2033
+ cell_data = _create_chip_cell_data(chips, default_chip_type)
2034
+ if cell_data is not None:
2035
+ updates.append((start_r, start_c, cell_data))
2036
+ return updates
2037
+
2038
+ num_cols = (end_col - start_c + 1) if end_col is not None else None
2039
+ num_rows = (end_row - start_r + 1) if end_row is not None else None
2040
+ is_2d_grid = (num_cols is None or num_cols > 1) and (
2041
+ num_rows is None or num_rows > 1
2042
+ )
2043
+
2044
+ # Case 2: 2D table grid (where chips is a list of rows)
2045
+ if (
2046
+ is_2d_grid
2047
+ and isinstance(chips, list)
2048
+ and len(chips) > 0
2049
+ and isinstance(chips[0], list)
2050
+ ):
2051
+ if end_row is not None and (start_r + len(chips) - 1) > end_row:
2052
+ raise UserInputError(
2053
+ f"2D chips row count ({len(chips)}) exceeds target range row bound ({num_rows} rows)."
2054
+ )
2055
+ for r_offset, row in enumerate(chips):
2056
+ r_idx = start_r + r_offset
2057
+ if end_col is not None and (start_c + len(row) - 1) > end_col:
2058
+ raise UserInputError(
2059
+ f"2D chips column count ({len(row)}) exceeds target range column bound ({num_cols} cols)."
2060
+ )
2061
+ for c_offset, item in enumerate(row):
2062
+ c_idx = start_c + c_offset
2063
+ cell_data = _create_chip_cell_data(item, default_chip_type)
2064
+ if cell_data is not None:
2065
+ updates.append((r_idx, c_idx, cell_data))
2066
+ return updates
2067
+
2068
+ # Case 3: 1D list of items (each item can be a single chip or a list of chips for that cell)
2069
+ if isinstance(chips, list):
2070
+ if is_single_row and not is_single_col:
2071
+ # Horizontal fill (e.g. A1:C1)
2072
+ if end_col is not None and (start_c + len(chips) - 1) > end_col:
2073
+ raise UserInputError(
2074
+ f"Number of chips ({len(chips)}) exceeds horizontal range capacity ({end_col - start_c + 1} cells)."
2075
+ )
2076
+ for c_offset, item in enumerate(chips):
2077
+ c_idx = start_c + c_offset
2078
+ cell_data = _create_chip_cell_data(item, default_chip_type)
2079
+ if cell_data is not None:
2080
+ updates.append((start_r, c_idx, cell_data))
2081
+ elif is_single_col or (end_row is None and end_col is None):
2082
+ # Vertical fill (e.g. F3:F23 or F3:F)
2083
+ if end_row is not None and (start_r + len(chips) - 1) > end_row:
2084
+ raise UserInputError(
2085
+ f"Number of chips ({len(chips)}) exceeds vertical range capacity ({end_row - start_r + 1} cells)."
2086
+ )
2087
+ for r_offset, item in enumerate(chips):
2088
+ r_idx = start_r + r_offset
2089
+ cell_data = _create_chip_cell_data(item, default_chip_type)
2090
+ if cell_data is not None:
2091
+ updates.append((r_idx, start_c, cell_data))
2092
+ else:
2093
+ # 2D range in row-major order
2094
+ ncols = num_cols if num_cols is not None else 1
2095
+ nrows = num_rows if num_rows is not None else 1
2096
+ max_capacity = ncols * nrows
2097
+ if end_row is not None and len(chips) > max_capacity:
2098
+ raise UserInputError(
2099
+ f"Number of chips ({len(chips)}) exceeds 2D range capacity ({max_capacity} cells)."
2100
+ )
2101
+ for i, item in enumerate(chips):
2102
+ r_idx = start_r + (i // ncols)
2103
+ c_idx = start_c + (i % ncols)
2104
+ cell_data = _create_chip_cell_data(item, default_chip_type)
2105
+ if cell_data is not None:
2106
+ updates.append((r_idx, c_idx, cell_data))
2107
+ return updates
2108
+
2109
+ # Case 4: Single item (string or dict) for a multi-cell range -> fill all cells in range
2110
+ single_cell_data = _create_chip_cell_data(chips, default_chip_type)
2111
+ if single_cell_data is None:
2112
+ return []
2113
+
2114
+ if end_row is not None and end_col is not None:
2115
+ for r_idx in range(start_r, end_row + 1):
2116
+ for c_idx in range(start_c, end_col + 1):
2117
+ updates.append((r_idx, c_idx, single_cell_data))
2118
+ else:
2119
+ updates.append((start_r, start_c, single_cell_data))
2120
+
2121
+ return updates
2122
+
2123
+
2124
+ def _find_named_range(
2125
+ named_ranges: List[dict],
2126
+ target_id: Optional[str] = None,
2127
+ target_name: Optional[str] = None,
2128
+ ) -> Optional[dict]:
2129
+ """Find a named range in a list of named ranges by ID or name.
2130
+
2131
+ Matches by target_id first if provided, then by target_name (exact match first,
2132
+ then case-insensitive match).
2133
+ """
2134
+ if target_id:
2135
+ target_id_str = str(target_id).strip()
2136
+ for nr in named_ranges:
2137
+ if nr.get("namedRangeId") == target_id_str:
2138
+ return nr
2139
+
2140
+ if target_name:
2141
+ name_clean = target_name.strip()
2142
+ name_lower = name_clean.lower()
2143
+ # Exact match
2144
+ for nr in named_ranges:
2145
+ if nr.get("name") == name_clean:
2146
+ return nr
2147
+ # Case-insensitive match fallback
2148
+ for nr in named_ranges:
2149
+ if (nr.get("name") or "").strip().lower() == name_lower:
2150
+ return nr
2151
+
2152
+ return None
2153
+
2154
+
2155
+ def _format_named_ranges_list(
2156
+ named_ranges: List[dict],
2157
+ sheet_titles: dict[int, str],
2158
+ spreadsheet_id: str,
2159
+ user_google_email: str,
2160
+ ) -> str:
2161
+ """Format a list of named ranges into a human-readable markdown table."""
2162
+ if not named_ranges:
2163
+ return f"No named ranges found in spreadsheet '{spreadsheet_id}' for {user_google_email}."
2164
+
2165
+ header = (
2166
+ f"Found {len(named_ranges)} named range(s) in spreadsheet '{spreadsheet_id}' for {user_google_email}:\n\n"
2167
+ "| Name | Range | Named Range ID |\n"
2168
+ "| :--- | :--- | :--- |\n"
2169
+ )
2170
+ rows = []
2171
+ for nr in named_ranges:
2172
+ nr_name = nr.get("name", "(unnamed)")
2173
+ nr_id = nr.get("namedRangeId", "(unknown)")
2174
+ grid_range = nr.get("range", {})
2175
+ a1_repr = _grid_range_to_a1(grid_range, sheet_titles)
2176
+ rows.append(f"| {nr_name} | {a1_repr} | {nr_id} |")
2177
+
2178
+ return header + "\n".join(rows)
2179
+
2180
+
2181
+ def _build_insert_comment_request(
2182
+ cell: str, sheets: List[dict], comment_content: str
2183
+ ) -> dict:
2184
+ """Build an insertComment request anchored to a single A1 cell."""
2185
+ grid_range = _parse_a1_range(cell, sheets)
2186
+ start_row = grid_range.get("startRowIndex")
2187
+ start_col = grid_range.get("startColumnIndex")
2188
+ is_single_cell = (
2189
+ start_row is not None
2190
+ and start_col is not None
2191
+ and grid_range.get("endRowIndex") == start_row + 1
2192
+ and grid_range.get("endColumnIndex") == start_col + 1
2193
+ )
2194
+ if not is_single_cell:
2195
+ raise UserInputError(
2196
+ f"cell must reference a single cell (e.g., 'Sheet1!B2'), got '{cell}'."
2197
+ )
2198
+ return {
2199
+ "insertComment": {
2200
+ "content": comment_content,
2201
+ "coordinate": {
2202
+ "sheetId": grid_range["sheetId"],
2203
+ "rowIndex": start_row,
2204
+ "columnIndex": start_col,
2205
+ },
2206
+ }
2207
+ }
2208
+
2209
+
2210
+ async def _insert_cell_comment(
2211
+ sheets_service, spreadsheet_id: str, cell: str, comment_content: str
2212
+ ) -> str:
2213
+ """Create a comment anchored to a cell via the Sheets API; return its ID."""
2214
+ metadata = await asyncio.to_thread(
2215
+ sheets_service.spreadsheets()
2216
+ .get(spreadsheetId=spreadsheet_id, fields="sheets(properties(sheetId,title))")
2217
+ .execute
2218
+ )
2219
+ request = _build_insert_comment_request(
2220
+ cell, metadata.get("sheets", []), comment_content
2221
+ )
2222
+
2223
+ response = await asyncio.to_thread(
2224
+ sheets_service.spreadsheets()
2225
+ .batchUpdate(spreadsheetId=spreadsheet_id, body={"requests": [request]})
2226
+ .execute
2227
+ )
2228
+
2229
+ replies = response.get("replies") or [{}]
2230
+ thread = replies[0].get("insertComment", {}).get("commentThread", {})
2231
+ comment_id = thread.get("commentId")
2232
+ if not comment_id:
2233
+ raise RuntimeError(
2234
+ f"Sheets API did not return a comment ID for {cell}; check list_spreadsheet_comments before retrying."
2235
+ )
2236
+ return comment_id