omni-dev 0.46.0

AI-powered git commit rewriter, PR generator, and MCP server for Jira, Confluence, Datadog, Gmail, and Drive.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
//! Sheets v4 API façade — typed wrappers over the handful of endpoints the
//! CLI needs, mirroring `crate::drive::files_api::FilesApi`'s shape.
//!
//! Free `build_*_url` functions take a literal `base_url` so they are
//! unit-testable without a client, exactly like `files_api.rs`'s.

use anyhow::{Context, Result};
use url::Url;

use crate::drive::api_client::GoogleApiClient;
use crate::drive::files_api::{append_write_scope_hint, WriteCapability};
use crate::drive::sheets::a1;
use crate::drive::sheets::client::SheetsClient;
use crate::drive::sheets::types::{
    AppendValuesResponse, BatchGetValuesResponse, BatchUpdateRequest, BatchUpdateRequestItem,
    BatchUpdateResponse, ClearValuesResponse, CopySheetToAnotherSpreadsheetRequest, DataFilter,
    SearchDeveloperMetadataRequest, SearchDeveloperMetadataResponse, SheetProperties, Spreadsheet,
    UpdateValuesResponse, ValueRange,
};

/// What a 2xx `spreadsheets.batchUpdate` produced (issues #2021, #1929).
///
/// A non-2xx is not represented here: it is the `Err` of
/// [`SheetsApi::batch_update`]. Making the two 2xx cases a type, rather than a
/// downcastable marker on the error, means every engine must decide what to
/// say about an applied-but-unreadable reply — and, because both are `Ok`,
/// `conclude_native_leased_write` refreshes the lease ledger and audits
/// `allowed` for both, as it must for a mutation that really happened.
#[derive(Debug)]
pub(in crate::drive) enum BatchUpdateOutcome {
    /// 2xx and the reply parsed.
    Applied(BatchUpdateResponse),
    /// 2xx — the mutation **was applied** — but the body could not be read or
    /// deserialised. `detail` carries the read/serde error.
    AppliedReplyUnreadable {
        /// Why the reply could not be read.
        detail: String,
    },
}

/// Whether running a verb's request a second time is safe, for the retry
/// advice in [`applied_reply_unreadable_line`].
///
/// Defaults to [`Self::NotIdempotent`]: after a mutation, excess caution is
/// the cheaper mistake, because what it prevents is a silent duplicate.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(in crate::drive) enum RetryHint {
    /// A second run could create a duplicate, shift content or compound.
    NotIdempotent,
    /// A second run provably leaves the same end state.
    Idempotent,
}

/// The one human-readable line every engine renders for an
/// `AppliedReplyUnreadable` result (issue #2021). Shared so the 20 engines'
/// wording cannot drift, the same reason `recovery_note` is.
pub(in crate::drive) fn applied_reply_unreadable_line(
    summary: &str,
    book: &str,
    hint: RetryHint,
    detail: &str,
) -> String {
    let advice = match hint {
        RetryHint::NotIdempotent => "do not retry; check the spreadsheet first",
        RetryHint::Idempotent => "check the spreadsheet to confirm",
    };
    format!("Applied, but the reply could not be read: {summary} in {book} — {advice} ({detail})")
}

/// `fields` mask for `spreadsheets.get`.
///
/// **Not optional.** An unmasked `spreadsheets.get` embeds every cell of
/// every sheet in the response, so on a large workbook the difference
/// between sending this and not is an out-of-memory failure rather than a
/// slower request. We only ever need the tab list.
///
/// `properties.locale,timeZone,autoRecalc,iterativeCalculationSettings`
/// (issue #1836's `update-workbook-properties`) ride along on the base mask
/// rather than getting their own `SPREADSHEET_FIELDS_WITH_*` widening like
/// every other feature in this file: unlike a `sheets.*` list that grows
/// with workbook content (protected ranges, charts, named ranges, …), these
/// are four fixed scalar/small-object fields on the single `properties`
/// object already fetched for `properties.title`, so including them
/// unconditionally costs every other caller nothing measurable — and
/// `structure.rs`'s `structure()` has exactly one `get_spreadsheet` call
/// site shared by all fifteen `StructureVerb`s, so branching it per verb
/// would be new complexity for no real savings.
const SPREADSHEET_FIELDS: &str = "spreadsheetId,\
    properties(title,locale,timeZone,autoRecalc,iterativeCalculationSettings),\
    sheets.properties(sheetId,title,index,hidden,rightToLeft,gridProperties(rowCount,columnCount,frozenRowCount,frozenColumnCount,hideGridlines))";

/// `fields` mask for `spreadsheets.get` when protected ranges are needed
/// too (issue #1643's `list-protections`/`update-protection`/
/// `unprotect-range`, which must resolve an *existing* protection before
/// they can act on it). A superset of [`SPREADSHEET_FIELDS`], kept separate
/// so every other caller — `sheets info`, `structure.rs`, `format.rs`,
/// `validation.rs` — never pays for data it doesn't use.
const SPREADSHEET_FIELDS_WITH_PROTECTIONS: &str = "spreadsheetId,properties.title,\
    sheets.properties(sheetId,title,index,hidden,rightToLeft,gridProperties(rowCount,columnCount,frozenRowCount,frozenColumnCount,hideGridlines)),\
    sheets.protectedRanges(protectedRangeId,range,description,warningOnly,editors.users)";

/// `fields` mask for `spreadsheets.get` when the basic filter and filter
/// views are needed too (issue #1794's `set-basic-filter`/
/// `list-filter-views`/`update-filter-view`/`delete-filter-view`, which must
/// resolve an *existing* filter view before they can act on one). A
/// superset of [`SPREADSHEET_FIELDS`], kept separate for the same reason
/// [`SPREADSHEET_FIELDS_WITH_PROTECTIONS`] is.
const SPREADSHEET_FIELDS_WITH_FILTER_VIEWS: &str = "spreadsheetId,properties.title,\
    sheets.properties(sheetId,title,index,hidden,rightToLeft,gridProperties(rowCount,columnCount,frozenRowCount,frozenColumnCount,hideGridlines)),\
    sheets.basicFilter(range,sortSpecs,criteria),\
    sheets.filterViews(filterViewId,title,range,namedRangeId,tableId,sortSpecs,criteria)";

/// `fields` mask for `spreadsheets.get` when conditional format rules are
/// needed too (issue #1793's `add-conditional-format`/
/// `update-conditional-format`/`delete-conditional-format`/
/// `list-conditional-formats`, all four of which share one fetch — see
/// [`SheetsApi::get_spreadsheet_with_conditional_formats`]'s doc comment for
/// why `add` uses the same wider mask as the other three despite not
/// strictly needing it). A superset of [`SPREADSHEET_FIELDS`], kept separate
/// for the same reason [`SPREADSHEET_FIELDS_WITH_PROTECTIONS`] is.
const SPREADSHEET_FIELDS_WITH_CONDITIONAL_FORMATS: &str = "spreadsheetId,properties.title,\
    sheets.properties(sheetId,title,index,hidden,rightToLeft,gridProperties(rowCount,columnCount,frozenRowCount,frozenColumnCount,hideGridlines)),\
    sheets.conditionalFormats(ranges,booleanRule,gradientRule)";

/// `fields` mask for `spreadsheets.get` when named ranges are needed too
/// (issue #1796's `list-named-ranges`/`update-named-range`/
/// `delete-named-range`, which must resolve an *existing* named range by
/// name before they can act on one). A superset of [`SPREADSHEET_FIELDS`],
/// kept separate for the same reason as
/// [`SPREADSHEET_FIELDS_WITH_PROTECTIONS`]: every other caller never pays
/// for data it doesn't use. Named ranges are workbook-scoped, so
/// `namedRanges` sits at the top level, not nested under `sheets` the way
/// `protectedRanges` is.
const SPREADSHEET_FIELDS_WITH_NAMED_RANGES: &str = "spreadsheetId,properties.title,\
    sheets.properties(sheetId,title,index,hidden,rightToLeft,gridProperties(rowCount,columnCount,frozenRowCount,frozenColumnCount,hideGridlines)),\
    namedRanges(namedRangeId,name,range)";

/// `fields` mask for `spreadsheets.get` when charts and slicers are needed
/// too (issue #1797's `add-chart`/`update-chart`/`delete-chart`/
/// `list-charts`/`add-slicer`/`update-slicer`/`delete-slicer`/
/// `list-slicers`, all eight of which share one fetch, mirroring
/// `SPREADSHEET_FIELDS_WITH_CONDITIONAL_FORMATS`'s reuse across its four
/// verbs). Deliberately requests `sheets.charts`/`sheets.slicers`
/// **unmasked below the object level** — every other wider mask in this
/// file narrows to the specific sub-fields each verb reads, but
/// `update-chart` must merge onto the chart's *entire* existing spec (see
/// [`crate::drive::sheets::types::UpdateChartSpecRequest`]'s doc comment),
/// so nothing here can be safely left out. A superset of
/// [`SPREADSHEET_FIELDS`], kept separate for the same reason
/// [`SPREADSHEET_FIELDS_WITH_PROTECTIONS`] is.
const SPREADSHEET_FIELDS_WITH_EMBEDDED_OBJECTS: &str = "spreadsheetId,properties.title,\
    sheets.properties(sheetId,title,index,hidden,rightToLeft,gridProperties(rowCount,columnCount,frozenRowCount,frozenColumnCount,hideGridlines)),\
    sheets.charts,sheets.slicers";

/// `fields` mask for `spreadsheets.get` when every pivot table in the
/// workbook is needed (issue #1798's `list-pivot-tables`, which must scan
/// every sheet's grid data for a populated `pivotTable` property — there is
/// no index or list endpoint for pivot tables the way there is for
/// protected ranges or filter views). Requesting `pivotTable` alone (no
/// `formattedValue`) keeps the response to one `{}` per populated cell that
/// has no pivot, same order of cost as `sheets read`. A superset of
/// [`SPREADSHEET_FIELDS`], kept separate for the same reason
/// [`SPREADSHEET_FIELDS_WITH_PROTECTIONS`] is.
const SPREADSHEET_FIELDS_WITH_PIVOT_TABLES: &str = "spreadsheetId,properties.title,\
    sheets.properties(sheetId,title,index,hidden,rightToLeft,gridProperties(rowCount,columnCount,frozenRowCount,frozenColumnCount,hideGridlines)),\
    sheets.data(startRow,startColumn,rowData.values(pivotTable))";

/// `fields` mask for `spreadsheets.get` when only a single cell's pivot
/// table (and displayed value) is needed — `add-pivot-table`'s
/// occupied-anchor check and `delete-pivot-table`'s "currently:" preview,
/// both of which read exactly one cell rather than the whole workbook.
/// Paired with a `ranges=` query parameter scoping the response to that one
/// cell (see [`SheetsApi::get_cell_pivot`]), so this mask alone would still
/// return every sheet's grid data without it.
const CELL_PIVOT_FIELDS: &str = "spreadsheetId,properties.title,\
    sheets.properties(sheetId,title,index,hidden,rightToLeft,gridProperties(rowCount,columnCount,frozenRowCount,frozenColumnCount,hideGridlines)),\
    sheets.data(startRow,startColumn,rowData.values(pivotTable,formattedValue))";

/// `fields` mask for `spreadsheets.get` when a range's cell-level formatting
/// is needed (issue #1878's `read-cell-format`, the tool that answers
/// ADR-0083 §5's "does this verb move formatting?" question). Paired with a
/// `ranges=` query parameter scoping the response to the caller's range
/// (see [`SheetsApi::get_cell_formats`]), so this mask alone would still
/// return every sheet's grid data without it.
///
/// Covers background color, text format (bold/italic/strikethrough/
/// underline/color), number format, horizontal alignment, the four cell
/// borders, notes and data validation. Deliberately **`userEnteredFormat`,
/// not `effectiveFormat`** — see
/// [`crate::drive::sheets::types::CellSnapshot::user_entered_format`]'s doc
/// comment.
///
/// Borders are included even though ADR-0083 §5's four checked properties
/// (background, bold, note, validation-presence) don't strictly need them:
/// a border is still part of `userEnteredFormat`, so a verb that moves only
/// borders would otherwise show as "no formatting changed" and be wrongly
/// left ungated. **Merges are a separate cut** — `sheets.merges` is a
/// different mask path entirely (a per-sheet list, not a per-cell
/// property), so they need their own field and outcome shape; deferred as
/// a follow-up (issue #1878's own open question).
const CELL_FORMAT_FIELDS: &str = "spreadsheetId,properties.title,\
    sheets.properties(sheetId,title,index,hidden,rightToLeft,gridProperties(rowCount,columnCount,frozenRowCount,frozenColumnCount,hideGridlines)),\
    sheets.data(startRow,startColumn,rowData.values(userEnteredFormat(backgroundColorStyle,textFormat(bold,italic,strikethrough,underline,foregroundColorStyle),numberFormat,horizontalAlignment,borders(top,bottom,left,right)),note,dataValidation))";

/// `fields` mask for `spreadsheets.get` when banded ranges are needed too
/// (issue #1832's `add-banding`/`update-banding`/`delete-banding`/
/// `list-bandings`, which must resolve an *existing* banded range by id
/// before three of the four can act on one). A superset of
/// [`SPREADSHEET_FIELDS`], kept separate for the same reason
/// [`SPREADSHEET_FIELDS_WITH_PROTECTIONS`] is.
const SPREADSHEET_FIELDS_WITH_BANDING: &str = "spreadsheetId,properties.title,\
    sheets.properties(sheetId,title,index,hidden,rightToLeft,gridProperties(rowCount,columnCount,frozenRowCount,frozenColumnCount,hideGridlines)),\
    sheets.bandedRanges(bandedRangeId,range,rowProperties,columnProperties)";

/// `fields` mask for `spreadsheets.get` when dimension groups are needed
/// too (issue #1833's `add-dimension-group`/`update-dimension-group`/
/// `delete-dimension-group`/`list-dimension-groups`, which must resolve an
/// *existing* group by its `(range, depth)` before three of the four can
/// act on one). A superset of [`SPREADSHEET_FIELDS`], kept separate for
/// the same reason [`SPREADSHEET_FIELDS_WITH_BANDING`] is.
const SPREADSHEET_FIELDS_WITH_DIMENSION_GROUPS: &str = "spreadsheetId,properties.title,\
    sheets.properties(sheetId,title,index,hidden,gridProperties(rowCount,columnCount)),\
    sheets.rowGroups(range,depth,collapsed),sheets.columnGroups(range,depth,collapsed)";

/// Maximum ranges sent in a single `values.batchGet`.
///
/// Each range is a percent-encoded, quoted sheet title in the query string,
/// so a workbook with hundreds of tabs would otherwise build a URL past what
/// servers and proxies accept. Chunking keeps each request bounded; the
/// engine stitches the chunks back together.
pub(crate) const MAX_RANGES_PER_BATCH: usize = 50;

/// How the API should render cell values.
///
/// Engine-layer, deliberately free of any `clap` derive — the CLI keeps its
/// own `ValueEnum` mirror, the same split `crate::cli::drive::permissions::check`
/// uses for `DriveOperation`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ValueRenderOption {
    /// Locale-formatted strings, as displayed in the UI (`"1,234.50"`,
    /// `"$5.00"`). The default because it matches both the spreadsheet as
    /// the user sees it and what `drive read --content`'s CSV export already
    /// produces for a Sheet today.
    #[default]
    Formatted,
    /// Raw typed values — JSON numbers and booleans rather than strings.
    /// What you want when feeding the output to something that will do
    /// arithmetic on it.
    Unformatted,
    /// The formula text (`=SUM(A1:A3)`) rather than its result.
    Formula,
}

impl ValueRenderOption {
    /// The wire value for the `valueRenderOption` query parameter.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Formatted => "FORMATTED_VALUE",
            Self::Unformatted => "UNFORMATTED_VALUE",
            Self::Formula => "FORMULA",
        }
    }
}

/// How the API should interpret the values being written.
///
/// Engine-layer, `clap`-free, like [`ValueRenderOption`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ValueInputOption {
    /// Parse each value the way typing it into the UI would: `=SUM(A1:A3)`
    /// becomes a formula, `2026-09-06` becomes a date, `1,234` becomes a
    /// number.
    ///
    /// The default because it is what a person means by "write this into the
    /// sheet". It is also the one option whose *wrong* value silently
    /// mangles data rather than erroring — neither choice fails, you just
    /// get formulas you meant as text or the reverse — which is why both
    /// spellings are spelled out in `--help` and in `docs/drive.md`. Note
    /// `--dry-run` does *not* echo it: there is no wrong-looking output to
    /// spot, so it has to be chosen deliberately.
    #[default]
    UserEntered,
    /// Store every value verbatim as a string. A leading `=` stays literal
    /// text rather than becoming a formula.
    Raw,
}

impl ValueInputOption {
    /// The wire value for the `valueInputOption` query parameter.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::UserEntered => "USER_ENTERED",
            Self::Raw => "RAW",
        }
    }
}

/// Sheets API façade.
#[derive(Debug)]
pub struct SheetsApi<'a> {
    client: &'a SheetsClient,
}

impl<'a> SheetsApi<'a> {
    /// Wraps an existing [`SheetsClient`].
    #[must_use]
    pub fn new(client: &'a SheetsClient) -> Self {
        Self { client }
    }

    /// Fetches a spreadsheet's metadata — its title and the list of sheets.
    ///
    /// Always `fields`-masked; see [`SPREADSHEET_FIELDS`].
    pub async fn get_spreadsheet(&self, spreadsheet_id: &str) -> Result<Spreadsheet> {
        let url = build_spreadsheet_get_url(self.client.base_url(), spreadsheet_id)?;
        self.client
            .transport()
            .get_parsed(url.as_str(), "Failed to parse Sheets spreadsheet metadata")
            .await
    }

    /// Fetches a spreadsheet's metadata **including protected ranges** —
    /// the one read the protection verbs need that no other caller does.
    /// See [`SPREADSHEET_FIELDS_WITH_PROTECTIONS`].
    pub async fn get_spreadsheet_with_protections(
        &self,
        spreadsheet_id: &str,
    ) -> Result<Spreadsheet> {
        let url =
            build_spreadsheet_get_with_protections_url(self.client.base_url(), spreadsheet_id)?;
        self.client
            .transport()
            .get_parsed(
                url.as_str(),
                "Failed to parse Sheets spreadsheet metadata (with protections)",
            )
            .await
    }

    /// Fetches a spreadsheet's metadata **including the basic filter and
    /// filter views** — the one read `filter.rs`'s verbs need that no other
    /// caller does. See [`SPREADSHEET_FIELDS_WITH_FILTER_VIEWS`].
    pub async fn get_spreadsheet_with_filter_views(
        &self,
        spreadsheet_id: &str,
    ) -> Result<Spreadsheet> {
        let url =
            build_spreadsheet_get_with_filter_views_url(self.client.base_url(), spreadsheet_id)?;
        self.client
            .transport()
            .get_parsed(
                url.as_str(),
                "Failed to parse Sheets spreadsheet metadata (with filter views)",
            )
            .await
    }

    /// Fetches a spreadsheet's metadata **including conditional format
    /// rules** — shared by all four `conditional_format.rs` verbs (issue
    /// #1793), mirroring [`Self::get_spreadsheet_with_protections`]'s reuse
    /// across all four protection verbs. `add-conditional-format` doesn't
    /// strictly need the existing list, but reusing this one fetch instead
    /// of adding a second, narrower one keeps `Sheet.conditional_formats`
    /// consistently populated whenever any conditional-format verb runs.
    /// See [`SPREADSHEET_FIELDS_WITH_CONDITIONAL_FORMATS`].
    pub async fn get_spreadsheet_with_conditional_formats(
        &self,
        spreadsheet_id: &str,
    ) -> Result<Spreadsheet> {
        let url = build_spreadsheet_get_with_conditional_formats_url(
            self.client.base_url(),
            spreadsheet_id,
        )?;
        self.client
            .transport()
            .get_parsed(
                url.as_str(),
                "Failed to parse Sheets spreadsheet metadata (with conditional formats)",
            )
            .await
    }

    /// Fetches a spreadsheet's metadata **including named ranges** — the
    /// one read the named-range verbs need that no other caller does. See
    /// [`SPREADSHEET_FIELDS_WITH_NAMED_RANGES`].
    pub async fn get_spreadsheet_with_named_ranges(
        &self,
        spreadsheet_id: &str,
    ) -> Result<Spreadsheet> {
        let url =
            build_spreadsheet_get_with_named_ranges_url(self.client.base_url(), spreadsheet_id)?;
        self.client
            .transport()
            .get_parsed(
                url.as_str(),
                "Failed to parse Sheets spreadsheet metadata (with named ranges)",
            )
            .await
    }

    /// Fetches a spreadsheet's metadata **including charts and slicers** —
    /// shared by all eight `embedded_object.rs` verbs (issue #1797), the
    /// same way [`Self::get_spreadsheet_with_conditional_formats`] is
    /// shared by its four. See
    /// [`SPREADSHEET_FIELDS_WITH_EMBEDDED_OBJECTS`].
    pub async fn get_spreadsheet_with_embedded_objects(
        &self,
        spreadsheet_id: &str,
    ) -> Result<Spreadsheet> {
        let url = build_spreadsheet_get_with_embedded_objects_url(
            self.client.base_url(),
            spreadsheet_id,
        )?;
        self.client
            .transport()
            .get_parsed(
                url.as_str(),
                "Failed to parse Sheets spreadsheet metadata (with embedded objects)",
            )
            .await
    }

    /// Fetches a spreadsheet's metadata **including every populated cell's
    /// `pivotTable` property** — `list-pivot-tables`' one fetch (issue
    /// #1798). See [`SPREADSHEET_FIELDS_WITH_PIVOT_TABLES`].
    pub async fn get_spreadsheet_with_pivot_tables(
        &self,
        spreadsheet_id: &str,
    ) -> Result<Spreadsheet> {
        let url =
            build_spreadsheet_get_with_pivot_tables_url(self.client.base_url(), spreadsheet_id)?;
        self.client
            .transport()
            .get_parsed(
                url.as_str(),
                "Failed to parse Sheets spreadsheet metadata (with pivot tables)",
            )
            .await
    }

    /// Fetches a spreadsheet's metadata **including banded ranges** —
    /// shared by all four `banding.rs` verbs (issue #1832), mirroring
    /// [`Self::get_spreadsheet_with_filter_views`]'s reuse across its own
    /// four verbs. See [`SPREADSHEET_FIELDS_WITH_BANDING`].
    pub async fn get_spreadsheet_with_banding(&self, spreadsheet_id: &str) -> Result<Spreadsheet> {
        let url = build_spreadsheet_get_with_banding_url(self.client.base_url(), spreadsheet_id)?;
        self.client
            .transport()
            .get_parsed(
                url.as_str(),
                "Failed to parse Sheets spreadsheet metadata (with banded ranges)",
            )
            .await
    }

    /// Fetches a spreadsheet's metadata **including dimension groups** —
    /// shared by all four `dimension_group.rs` verbs (issue #1833),
    /// mirroring [`Self::get_spreadsheet_with_banding`]'s reuse across its
    /// own four verbs. See [`SPREADSHEET_FIELDS_WITH_DIMENSION_GROUPS`].
    pub async fn get_spreadsheet_with_dimension_groups(
        &self,
        spreadsheet_id: &str,
    ) -> Result<Spreadsheet> {
        let url = build_spreadsheet_get_with_dimension_groups_url(
            self.client.base_url(),
            spreadsheet_id,
        )?;
        self.client
            .transport()
            .get_parsed(
                url.as_str(),
                "Failed to parse Sheets spreadsheet metadata (with dimension groups)",
            )
            .await
    }

    /// Fetches a single cell's `pivotTable` property and displayed value —
    /// `add-pivot-table`'s occupied-anchor check and `delete-pivot-table`'s
    /// "currently:" preview (issue #1798). `composed_a1` must be a
    /// single-cell A1 reference carrying its own `Sheet!` prefix; the
    /// response's `sheets` list still carries every sheet's properties (the
    /// mask's own `sheets.properties(...)` clause), but `sheets.data` is
    /// scoped to `composed_a1` by the `ranges` query parameter. See
    /// [`CELL_PIVOT_FIELDS`].
    pub async fn get_cell_pivot(
        &self,
        spreadsheet_id: &str,
        composed_a1: &str,
    ) -> Result<Spreadsheet> {
        let url = build_cell_pivot_get_url(self.client.base_url(), spreadsheet_id, composed_a1)?;
        self.client
            .transport()
            .get_parsed(url.as_str(), "Failed to parse Sheets cell pivot response")
            .await
    }

    /// Fetches a range's cell-level formatting — `read-cell-format` (issue
    /// #1878). `composed_a1` may be any range `a1::compose` can build, not
    /// just a single cell; the response's `sheets.data` is scoped to it by
    /// the `ranges` query parameter. See [`CELL_FORMAT_FIELDS`].
    pub async fn get_cell_formats(
        &self,
        spreadsheet_id: &str,
        composed_a1: &str,
    ) -> Result<Spreadsheet> {
        let url = build_cell_format_get_url(self.client.base_url(), spreadsheet_id, composed_a1)?;
        self.client
            .transport()
            .get_parsed(url.as_str(), "Failed to parse Sheets cell format response")
            .await
    }

    /// Fetches the cell values of a single A1 range.
    pub async fn values_get(
        &self,
        spreadsheet_id: &str,
        range: &str,
        render: ValueRenderOption,
    ) -> Result<ValueRange> {
        let url = build_values_get_url(self.client.base_url(), spreadsheet_id, range, render)?;
        self.client
            .transport()
            .get_parsed(url.as_str(), "Failed to parse Sheets values response")
            .await
    }

    /// Fetches the cell values of several A1 ranges in one request.
    ///
    /// Callers must match results on each [`ValueRange::range`], never on the
    /// order of `ranges` — see that field's docs.
    pub async fn values_batch_get(
        &self,
        spreadsheet_id: &str,
        ranges: &[String],
        render: ValueRenderOption,
    ) -> Result<BatchGetValuesResponse> {
        let url =
            build_values_batch_get_url(self.client.base_url(), spreadsheet_id, ranges, render)?;
        self.client
            .transport()
            .get_parsed(url.as_str(), "Failed to parse Sheets batchGet response")
            .await
    }

    /// Fetches every sheet named in `titles` via chunked `values.batchGet`,
    /// pairing each result with the sheet title the server echoed back —
    /// the "quote each title, batchGet in [`MAX_RANGES_PER_BATCH`]-sized
    /// chunks, resolve each result's title from its own echoed `range`"
    /// skeleton `read.rs::read_whole_workbook` and
    /// `named_range.rs::scan_referencing_formulas` both need, factored out
    /// once so a batching or echo-matching fix lands in one place.
    ///
    /// A result's title is `None`, never dropped, when
    /// [`crate::drive::sheets::a1::sheet_title_of`] can't parse it back out
    /// of the echoed range — the caller decides what that's worth, exactly
    /// as `read_whole_workbook`'s `order_by_workbook` already does.
    pub(crate) async fn batch_get_every_sheet(
        &self,
        spreadsheet_id: &str,
        titles: &[String],
        render: ValueRenderOption,
    ) -> Result<Vec<(Option<String>, ValueRange)>> {
        let mut out = Vec::with_capacity(titles.len());
        for chunk in titles.chunks(MAX_RANGES_PER_BATCH) {
            let ranges: Vec<String> = chunk.iter().map(|t| a1::quote_sheet_title(t)).collect();
            let response = self
                .values_batch_get(spreadsheet_id, &ranges, render)
                .await?;
            for value_range in response.value_ranges {
                let title = value_range.range.as_deref().and_then(a1::sheet_title_of);
                out.push((title, value_range));
            }
        }
        Ok(out)
    }

    /// Overwrites the cells of `range`.
    ///
    /// `pub(in crate::drive)` so the CLI cannot reach it without going
    /// through the gated engine — the same no-bypass-by-construction fence
    /// `FilesApi::create`/`upload`/`edit_content` sit behind.
    pub(in crate::drive) async fn values_update(
        &self,
        spreadsheet_id: &str,
        range: &str,
        values: &[Vec<String>],
        input: ValueInputOption,
    ) -> Result<UpdateValuesResponse> {
        let url = build_values_update_url(self.client.base_url(), spreadsheet_id, range, input)?;
        let body = serde_json::json!({ "range": range, "values": values });
        let response = self
            .client
            .transport()
            .put_json(url.as_str(), &body)
            .await?;
        self.client
            .transport()
            .parse_response(response, "Failed to parse Sheets update response")
            .await
            .map_err(|err| append_write_scope_hint(err, WriteCapability::EditContent))
    }

    /// Appends rows after the last row of the table containing `range`.
    pub(in crate::drive) async fn values_append(
        &self,
        spreadsheet_id: &str,
        range: &str,
        values: &[Vec<String>],
        input: ValueInputOption,
    ) -> Result<AppendValuesResponse> {
        let url = build_values_append_url(self.client.base_url(), spreadsheet_id, range, input)?;
        let body = serde_json::json!({ "range": range, "values": values });
        let response = self
            .client
            .transport()
            .post_json(url.as_str(), &body)
            .await?;
        self.client
            .transport()
            .parse_response(response, "Failed to parse Sheets append response")
            .await
            .map_err(|err| append_write_scope_hint(err, WriteCapability::EditContent))
    }

    /// Clears the values in `range`, leaving formatting intact.
    pub(in crate::drive) async fn values_clear(
        &self,
        spreadsheet_id: &str,
        range: &str,
    ) -> Result<ClearValuesResponse> {
        let url = build_values_clear_url(self.client.base_url(), spreadsheet_id, range)?;
        let response = self
            .client
            .transport()
            .post_json(url.as_str(), &serde_json::json!({}))
            .await?;
        self.client
            .transport()
            .parse_response(response, "Failed to parse Sheets clear response")
            .await
            .map_err(|err| append_write_scope_hint(err, WriteCapability::EditContent))
    }

    /// Applies structural `requests` to a spreadsheet (issue #1613).
    ///
    /// `pub(in crate::drive)` like the other mutating methods: that fence is
    /// what makes gate bypass impossible by construction, since no module
    /// outside `crate::drive` — where every engine runs the write gate first
    /// — can reach it.
    ///
    /// Takes already-built [`BatchUpdateRequestItem`]s rather than a raw
    /// JSON body, so the only requests expressible are the ones that type
    /// models. That is the type-level half of the guarantee its doc comment
    /// describes.
    ///
    /// `Err` means only that the server did **not** report success: a non-2xx,
    /// or a send/transport failure before any status arrived. A 2xx whose body
    /// cannot be read is [`BatchUpdateOutcome::AppliedReplyUnreadable`], returned as `Ok`
    /// (issue #2021), because the mutation happened. A timeout or connection
    /// reset before a status line stays `Err` too: the change may or may not
    /// have been applied, and this method cannot claim it was.
    pub(in crate::drive) async fn batch_update(
        &self,
        spreadsheet_id: &str,
        requests: Vec<BatchUpdateRequestItem>,
    ) -> Result<BatchUpdateOutcome> {
        let url = build_batch_update_url(self.client.base_url(), spreadsheet_id)?;
        let body = BatchUpdateRequest { requests };
        let response = self
            .client
            .transport()
            .post_json(url.as_str(), &body)
            .await?;
        let reply = self
            .client
            .transport()
            .parse_success_response::<BatchUpdateResponse>(
                response,
                "Failed to parse Sheets batchUpdate response",
            )
            .await
            .map_err(|err| append_write_scope_hint(err, WriteCapability::EditContent))?;
        Ok(match reply {
            Ok(response) => BatchUpdateOutcome::Applied(response),
            Err(detail) => BatchUpdateOutcome::AppliedReplyUnreadable { detail },
        })
    }

    /// Copies one sheet from `spreadsheet_id` into `destination_spreadsheet_id`
    /// (ADR-0080 §10 / issue #1676's typed native-document restore path — a
    /// deleted sheet's Drive-copy backup still contains it, so `drive lease
    /// restore` copies it straight back into the live spreadsheet rather
    /// than requiring a manual copy-back via the Drive UI).
    ///
    /// `pub(in crate::drive)` like the other mutating methods here — the
    /// same no-bypass-by-construction fence.
    pub(in crate::drive) async fn copy_to(
        &self,
        spreadsheet_id: &str,
        sheet_id: i64,
        destination_spreadsheet_id: &str,
    ) -> Result<SheetProperties> {
        let url = build_copy_to_url(self.client.base_url(), spreadsheet_id, sheet_id)?;
        let body = CopySheetToAnotherSpreadsheetRequest {
            destination_spreadsheet_id: destination_spreadsheet_id.to_string(),
        };
        let response = self
            .client
            .transport()
            .post_json(url.as_str(), &body)
            .await?;
        self.client
            .transport()
            .parse_response(response, "Failed to parse Sheets copyTo response")
            .await
            .map_err(|err| append_write_scope_hint(err, WriteCapability::EditContent))
    }

    /// Searches for developer-metadata entries matching `filters`
    /// (issue #1795, [ADR-0081](../../../docs/adrs/adr-0081.md) §4).
    ///
    /// Read-only, so — unlike [`Self::batch_update`]/[`Self::copy_to`] —
    /// this is plain `pub`, not `pub(in crate::drive)`, and never goes
    /// through [`append_write_scope_hint`]: nothing here mutates.
    /// `developer_metadata.rs` is the one caller, and it always includes
    /// `visibility: DOCUMENT_VISIBILITY` in every filter it builds, so the
    /// server itself never returns a `PROJECT`-visibility entry to begin
    /// with.
    pub async fn search_developer_metadata(
        &self,
        spreadsheet_id: &str,
        filters: Vec<DataFilter>,
    ) -> Result<SearchDeveloperMetadataResponse> {
        let url = build_developer_metadata_search_url(self.client.base_url(), spreadsheet_id)?;
        let body = SearchDeveloperMetadataRequest {
            data_filters: filters,
        };
        let response = self
            .client
            .transport()
            .post_json(url.as_str(), &body)
            .await?;
        self.client
            .transport()
            .parse_response(
                response,
                "Failed to parse Sheets developerMetadata.search response",
            )
            .await
    }
}

fn build_spreadsheet_get_url(base_url: &str, spreadsheet_id: &str) -> Result<Url> {
    let mut url = GoogleApiClient::api_url(base_url, "/v4/spreadsheets")
        .context("Invalid Sheets base URL")?;
    GoogleApiClient::push_path_segments(&mut url, &[spreadsheet_id])?;
    url.query_pairs_mut()
        .append_pair("fields", SPREADSHEET_FIELDS);
    Ok(url)
}

fn build_spreadsheet_get_with_protections_url(base_url: &str, spreadsheet_id: &str) -> Result<Url> {
    let mut url = GoogleApiClient::api_url(base_url, "/v4/spreadsheets")
        .context("Invalid Sheets base URL")?;
    GoogleApiClient::push_path_segments(&mut url, &[spreadsheet_id])?;
    url.query_pairs_mut()
        .append_pair("fields", SPREADSHEET_FIELDS_WITH_PROTECTIONS);
    Ok(url)
}

fn build_spreadsheet_get_with_filter_views_url(
    base_url: &str,
    spreadsheet_id: &str,
) -> Result<Url> {
    let mut url = GoogleApiClient::api_url(base_url, "/v4/spreadsheets")
        .context("Invalid Sheets base URL")?;
    GoogleApiClient::push_path_segments(&mut url, &[spreadsheet_id])?;
    url.query_pairs_mut()
        .append_pair("fields", SPREADSHEET_FIELDS_WITH_FILTER_VIEWS);
    Ok(url)
}

fn build_spreadsheet_get_with_conditional_formats_url(
    base_url: &str,
    spreadsheet_id: &str,
) -> Result<Url> {
    let mut url = GoogleApiClient::api_url(base_url, "/v4/spreadsheets")
        .context("Invalid Sheets base URL")?;
    GoogleApiClient::push_path_segments(&mut url, &[spreadsheet_id])?;
    url.query_pairs_mut()
        .append_pair("fields", SPREADSHEET_FIELDS_WITH_CONDITIONAL_FORMATS);
    Ok(url)
}

fn build_spreadsheet_get_with_named_ranges_url(
    base_url: &str,
    spreadsheet_id: &str,
) -> Result<Url> {
    let mut url = GoogleApiClient::api_url(base_url, "/v4/spreadsheets")
        .context("Invalid Sheets base URL")?;
    GoogleApiClient::push_path_segments(&mut url, &[spreadsheet_id])?;
    url.query_pairs_mut()
        .append_pair("fields", SPREADSHEET_FIELDS_WITH_NAMED_RANGES);
    Ok(url)
}

fn build_spreadsheet_get_with_embedded_objects_url(
    base_url: &str,
    spreadsheet_id: &str,
) -> Result<Url> {
    let mut url = GoogleApiClient::api_url(base_url, "/v4/spreadsheets")
        .context("Invalid Sheets base URL")?;
    GoogleApiClient::push_path_segments(&mut url, &[spreadsheet_id])?;
    url.query_pairs_mut()
        .append_pair("fields", SPREADSHEET_FIELDS_WITH_EMBEDDED_OBJECTS);
    Ok(url)
}

fn build_spreadsheet_get_with_pivot_tables_url(
    base_url: &str,
    spreadsheet_id: &str,
) -> Result<Url> {
    let mut url = GoogleApiClient::api_url(base_url, "/v4/spreadsheets")
        .context("Invalid Sheets base URL")?;
    GoogleApiClient::push_path_segments(&mut url, &[spreadsheet_id])?;
    url.query_pairs_mut()
        .append_pair("fields", SPREADSHEET_FIELDS_WITH_PIVOT_TABLES);
    Ok(url)
}

fn build_spreadsheet_get_with_banding_url(base_url: &str, spreadsheet_id: &str) -> Result<Url> {
    let mut url = GoogleApiClient::api_url(base_url, "/v4/spreadsheets")
        .context("Invalid Sheets base URL")?;
    GoogleApiClient::push_path_segments(&mut url, &[spreadsheet_id])?;
    url.query_pairs_mut()
        .append_pair("fields", SPREADSHEET_FIELDS_WITH_BANDING);
    Ok(url)
}

fn build_spreadsheet_get_with_dimension_groups_url(
    base_url: &str,
    spreadsheet_id: &str,
) -> Result<Url> {
    let mut url = GoogleApiClient::api_url(base_url, "/v4/spreadsheets")
        .context("Invalid Sheets base URL")?;
    GoogleApiClient::push_path_segments(&mut url, &[spreadsheet_id])?;
    url.query_pairs_mut()
        .append_pair("fields", SPREADSHEET_FIELDS_WITH_DIMENSION_GROUPS);
    Ok(url)
}

fn build_cell_pivot_get_url(
    base_url: &str,
    spreadsheet_id: &str,
    composed_a1: &str,
) -> Result<Url> {
    let mut url = GoogleApiClient::api_url(base_url, "/v4/spreadsheets")
        .context("Invalid Sheets base URL")?;
    GoogleApiClient::push_path_segments(&mut url, &[spreadsheet_id])?;
    url.query_pairs_mut()
        .append_pair("ranges", composed_a1)
        .append_pair("fields", CELL_PIVOT_FIELDS);
    Ok(url)
}

fn build_cell_format_get_url(
    base_url: &str,
    spreadsheet_id: &str,
    composed_a1: &str,
) -> Result<Url> {
    let mut url = GoogleApiClient::api_url(base_url, "/v4/spreadsheets")
        .context("Invalid Sheets base URL")?;
    GoogleApiClient::push_path_segments(&mut url, &[spreadsheet_id])?;
    url.query_pairs_mut()
        .append_pair("ranges", composed_a1)
        .append_pair("fields", CELL_FORMAT_FIELDS);
    Ok(url)
}

fn build_values_get_url(
    base_url: &str,
    spreadsheet_id: &str,
    range: &str,
    render: ValueRenderOption,
) -> Result<Url> {
    let mut url = GoogleApiClient::api_url(base_url, "/v4/spreadsheets")
        .context("Invalid Sheets base URL")?;
    GoogleApiClient::push_path_segments(&mut url, &[spreadsheet_id, "values", range])?;
    url.query_pairs_mut()
        .append_pair("valueRenderOption", render.as_str());
    Ok(url)
}

fn build_values_batch_get_url(
    base_url: &str,
    spreadsheet_id: &str,
    ranges: &[String],
    render: ValueRenderOption,
) -> Result<Url> {
    anyhow::ensure!(
        !ranges.is_empty(),
        "values.batchGet requires at least one range"
    );
    anyhow::ensure!(
        ranges.len() <= MAX_RANGES_PER_BATCH,
        "values.batchGet was given {} ranges, over the {MAX_RANGES_PER_BATCH} per-request cap; \
         callers must chunk",
        ranges.len()
    );
    let mut url = GoogleApiClient::api_url(base_url, "/v4/spreadsheets")
        .context("Invalid Sheets base URL")?;
    // `:batchGet` is a suffix on the `values` segment, not a segment of its
    // own; `:` carries no meaning inside a path segment so it survives
    // encoding untouched.
    GoogleApiClient::push_path_segments(&mut url, &[spreadsheet_id, "values:batchGet"])?;
    {
        let mut pairs = url.query_pairs_mut();
        for range in ranges {
            pairs.append_pair("ranges", range);
        }
        pairs.append_pair("valueRenderOption", render.as_str());
    }
    Ok(url)
}

fn build_values_update_url(
    base_url: &str,
    spreadsheet_id: &str,
    range: &str,
    input: ValueInputOption,
) -> Result<Url> {
    let mut url = GoogleApiClient::api_url(base_url, "/v4/spreadsheets")
        .context("Invalid Sheets base URL")?;
    GoogleApiClient::push_path_segments(&mut url, &[spreadsheet_id, "values", range])?;
    url.query_pairs_mut()
        .append_pair("valueInputOption", input.as_str());
    Ok(url)
}

fn build_values_append_url(
    base_url: &str,
    spreadsheet_id: &str,
    range: &str,
    input: ValueInputOption,
) -> Result<Url> {
    let mut url = GoogleApiClient::api_url(base_url, "/v4/spreadsheets")
        .context("Invalid Sheets base URL")?;
    GoogleApiClient::push_path_segments(
        &mut url,
        &[spreadsheet_id, "values", &format!("{range}:append")],
    )?;
    {
        let mut pairs = url.query_pairs_mut();
        pairs.append_pair("valueInputOption", input.as_str());
        // Insert whole rows rather than overwriting whatever sits below the
        // table; `OVERWRITE` is the API default and is the destructive one.
        pairs.append_pair("insertDataOption", "INSERT_ROWS");
    }
    Ok(url)
}

fn build_values_clear_url(base_url: &str, spreadsheet_id: &str, range: &str) -> Result<Url> {
    let mut url = GoogleApiClient::api_url(base_url, "/v4/spreadsheets")
        .context("Invalid Sheets base URL")?;
    GoogleApiClient::push_path_segments(
        &mut url,
        &[spreadsheet_id, "values", &format!("{range}:clear")],
    )?;
    Ok(url)
}

/// `POST /v4/spreadsheets/{id}:batchUpdate`.
///
/// Unlike the `values.*` builders, nothing caller-influenced reaches the
/// path — a spreadsheet id is `[A-Za-z0-9_-]`. The `:batchUpdate` suffix
/// rides the id segment, following the `values:batchGet` precedent above;
/// `:` carries no meaning inside a path segment, so it survives encoding.
fn build_batch_update_url(base_url: &str, spreadsheet_id: &str) -> Result<Url> {
    let mut url = GoogleApiClient::api_url(base_url, "/v4/spreadsheets")
        .context("Invalid Sheets base URL")?;
    GoogleApiClient::push_path_segments(&mut url, &[&format!("{spreadsheet_id}:batchUpdate")])?;
    Ok(url)
}

/// `POST /v4/spreadsheets/{spreadsheetId}/sheets/{sheetId}:copyTo`.
///
/// The `:copyTo` suffix rides the sheet-id segment, same reasoning as
/// [`build_batch_update_url`]'s `:batchUpdate` suffix — a sheet id is a
/// plain integer, so nothing caller-influenced reaches the path here either.
fn build_copy_to_url(base_url: &str, spreadsheet_id: &str, sheet_id: i64) -> Result<Url> {
    let mut url = GoogleApiClient::api_url(base_url, "/v4/spreadsheets")
        .context("Invalid Sheets base URL")?;
    GoogleApiClient::push_path_segments(
        &mut url,
        &[spreadsheet_id, "sheets", &format!("{sheet_id}:copyTo")],
    )?;
    Ok(url)
}

/// `POST /v4/spreadsheets/{spreadsheetId}/developerMetadata:search`.
///
/// Same `:suffix`-on-segment trick as [`build_copy_to_url`]'s `:copyTo` —
/// `spreadsheet_id` is always `[A-Za-z0-9_-]`, so nothing caller-controlled
/// reaches the path unescaped.
fn build_developer_metadata_search_url(base_url: &str, spreadsheet_id: &str) -> Result<Url> {
    let mut url = GoogleApiClient::api_url(base_url, "/v4/spreadsheets")
        .context("Invalid Sheets base URL")?;
    GoogleApiClient::push_path_segments(&mut url, &[spreadsheet_id, "developerMetadata:search"])?;
    Ok(url)
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;

    const BASE: &str = "https://sheets.googleapis.com";

    // ── spreadsheets.get ───────────────────────────────────────────────

    #[test]
    fn spreadsheet_get_url_masks_fields() {
        let url = build_spreadsheet_get_url(BASE, "sheet-1").unwrap();
        assert_eq!(url.path(), "/v4/spreadsheets/sheet-1");
        let fields = url
            .query_pairs()
            .find(|(k, _)| k == "fields")
            .map(|(_, v)| v.to_string())
            .expect("fields mask must always be sent");
        assert!(fields.contains("sheets.properties"));
        assert!(fields.contains("title"));
        // issue #1835: frozen rows/columns/hidden-gridlines/rightToLeft ride
        // the same `sheets.properties` sub-mask every constant shares.
        assert!(fields.contains("frozenRowCount"));
    }

    #[test]
    fn spreadsheet_get_with_conditional_formats_url_masks_the_wider_fields() {
        let url = build_spreadsheet_get_with_conditional_formats_url(BASE, "sheet-1").unwrap();
        assert_eq!(url.path(), "/v4/spreadsheets/sheet-1");
        let fields = url
            .query_pairs()
            .find(|(k, _)| k == "fields")
            .map(|(_, v)| v.to_string())
            .expect("fields mask must always be sent");
        assert!(fields.contains("sheets.conditionalFormats"));
        assert!(fields.contains("booleanRule"));
        assert!(fields.contains("gradientRule"));
        // issue #1835: every SPREADSHEET_FIELDS* constant carries the same
        // sheets.properties sub-mask, so this one must too.
        assert!(fields.contains("frozenRowCount"));
    }

    #[tokio::test]
    async fn get_spreadsheet_with_embedded_objects_surfaces_an_unparseable_base_url() {
        // The `?` on the URL builder is the only failure this method can
        // reach before the network call, so a base URL the `url` crate
        // cannot parse is what exercises it — and it must surface as an
        // error, never a panic.
        use crate::drive::auth::{DriveCredentials, DriveGrantedScopes};
        use crate::drive::client::DriveClient;
        use crate::drive::sheets::client::SHEETS_API_URL;
        use crate::test_support::env::MapEnv;
        use crate::utils::secret::Secret;

        let credentials = DriveCredentials {
            client_id: "client-1".to_string(),
            client_secret: Secret::new("secret-1"),
            refresh_token: Secret::new("refresh-1"),
            scope: DriveGrantedScopes::READONLY,
        };
        let drive = DriveClient::new("https://www.googleapis.com", &credentials).unwrap();
        let env = MapEnv::new().with(SHEETS_API_URL, "not a url");
        let sheets = SheetsClient::from_drive_client_with(&env, &drive).unwrap();

        let err = SheetsApi::new(&sheets)
            .get_spreadsheet_with_embedded_objects("sheet-1")
            .await
            .unwrap_err();
        assert!(
            err.to_string().contains("Invalid Sheets base URL"),
            "{err:#}"
        );
    }

    #[test]
    fn spreadsheet_get_with_embedded_objects_url_masks_the_wider_fields() {
        let url = build_spreadsheet_get_with_embedded_objects_url(BASE, "sheet-1").unwrap();
        assert_eq!(url.path(), "/v4/spreadsheets/sheet-1");
        let fields = url
            .query_pairs()
            .find(|(k, _)| k == "fields")
            .map(|(_, v)| v.to_string())
            .expect("fields mask must always be sent");
        assert!(fields.contains("sheets.charts"));
        assert!(fields.contains("sheets.slicers"));
        // issue #1835: every SPREADSHEET_FIELDS* constant carries the same
        // sheets.properties sub-mask, so this one must too.
        assert!(fields.contains("frozenRowCount"));
    }

    #[test]
    fn spreadsheet_get_with_pivot_tables_url_masks_the_wider_fields() {
        let url = build_spreadsheet_get_with_pivot_tables_url(BASE, "sheet-1").unwrap();
        assert_eq!(url.path(), "/v4/spreadsheets/sheet-1");
        let fields = url
            .query_pairs()
            .find(|(k, _)| k == "fields")
            .map(|(_, v)| v.to_string())
            .expect("fields mask must always be sent");
        assert!(fields.contains("sheets.data"));
        assert!(fields.contains("pivotTable"));
        assert!(!fields.contains("formattedValue"));
        // issue #1835: every SPREADSHEET_FIELDS* constant carries the same
        // sheets.properties sub-mask, so this one must too.
        assert!(fields.contains("frozenRowCount"));
    }

    #[tokio::test]
    async fn get_spreadsheet_with_dimension_groups_surfaces_an_unparseable_base_url() {
        // Same reasoning as
        // `get_spreadsheet_with_embedded_objects_surfaces_an_unparseable_base_url`:
        // the `?` on this URL builder is the only failure this method can
        // reach before the network call.
        use crate::drive::auth::{DriveCredentials, DriveGrantedScopes};
        use crate::drive::client::DriveClient;
        use crate::drive::sheets::client::SHEETS_API_URL;
        use crate::test_support::env::MapEnv;
        use crate::utils::secret::Secret;

        let credentials = DriveCredentials {
            client_id: "client-1".to_string(),
            client_secret: Secret::new("secret-1"),
            refresh_token: Secret::new("refresh-1"),
            scope: DriveGrantedScopes::READONLY,
        };
        let drive = DriveClient::new("https://www.googleapis.com", &credentials).unwrap();
        let env = MapEnv::new().with(SHEETS_API_URL, "not a url");
        let sheets = SheetsClient::from_drive_client_with(&env, &drive).unwrap();

        let err = SheetsApi::new(&sheets)
            .get_spreadsheet_with_dimension_groups("sheet-1")
            .await
            .unwrap_err();
        assert!(
            err.to_string().contains("Invalid Sheets base URL"),
            "{err:#}"
        );
    }

    #[test]
    fn spreadsheet_get_with_dimension_groups_url_masks_the_wider_fields() {
        let url = build_spreadsheet_get_with_dimension_groups_url(BASE, "sheet-1").unwrap();
        assert_eq!(url.path(), "/v4/spreadsheets/sheet-1");
        let fields = url
            .query_pairs()
            .find(|(k, _)| k == "fields")
            .map(|(_, v)| v.to_string())
            .expect("fields mask must always be sent");
        assert!(fields.contains("rowGroups"));
        assert!(fields.contains("columnGroups"));
    }

    #[test]
    fn cell_pivot_get_url_scopes_ranges_and_masks_fields() {
        let url = build_cell_pivot_get_url(BASE, "sheet-1", "'Report'!A1").unwrap();
        assert_eq!(url.path(), "/v4/spreadsheets/sheet-1");
        let ranges = url
            .query_pairs()
            .find(|(k, _)| k == "ranges")
            .map(|(_, v)| v.to_string())
            .expect("ranges must always be sent");
        assert_eq!(ranges, "'Report'!A1");
        let fields = url
            .query_pairs()
            .find(|(k, _)| k == "fields")
            .map(|(_, v)| v.to_string())
            .expect("fields mask must always be sent");
        assert!(fields.contains("pivotTable"));
        assert!(fields.contains("formattedValue"));
        // issue #1835: CELL_PIVOT_FIELDS carries the same sheets.properties
        // sub-mask every other SPREADSHEET_FIELDS* constant does.
        assert!(fields.contains("frozenRowCount"));
    }

    #[test]
    fn cell_format_get_url_scopes_ranges_and_masks_fields() {
        let url = build_cell_format_get_url(BASE, "sheet-1", "'Report'!A1:D10").unwrap();
        assert_eq!(url.path(), "/v4/spreadsheets/sheet-1");
        let ranges = url
            .query_pairs()
            .find(|(k, _)| k == "ranges")
            .map(|(_, v)| v.to_string())
            .expect("ranges must always be sent");
        assert_eq!(ranges, "'Report'!A1:D10");
        let fields = url
            .query_pairs()
            .find(|(k, _)| k == "fields")
            .map(|(_, v)| v.to_string())
            .expect("fields mask must always be sent");
        assert!(fields.contains("userEnteredFormat"));
        assert!(fields.contains("backgroundColorStyle"));
        assert!(fields.contains("borders(top,bottom,left,right)"));
        assert!(fields.contains("note"));
        assert!(fields.contains("dataValidation"));
        // issue #1878: read userEnteredFormat, never effectiveFormat — the
        // latter folds in conditional formatting and would give false
        // positives when checking whether a verb moved formatting.
        assert!(!fields.contains("effectiveFormat"));
        assert!(!fields.contains("formattedValue"));
        assert!(fields.contains("frozenRowCount"));
    }

    // ── values.get: encoding is the whole point ────────────────────────

    #[test]
    fn values_get_url_percent_encodes_a_space_in_a_quoted_title() {
        let url = build_values_get_url(
            BASE,
            "sheet-1",
            "'My Sheet'!A1:B2",
            ValueRenderOption::Formatted,
        )
        .unwrap();
        assert!(
            url.as_str().contains("'My%20Sheet'!A1:B2"),
            "space must be encoded: {url}"
        );
    }

    #[test]
    fn values_get_url_encodes_characters_that_would_reshape_the_url() {
        // Each of these silently corrupts the request if interpolated raw:
        // `#` truncates to a fragment, `?` starts a query, `/` invents a
        // path segment.
        for (title, encoded) in [("A#B", "%23"), ("A?B", "%3F"), ("A/B", "%2F")] {
            let range = format!("'{title}'!A1");
            let url =
                build_values_get_url(BASE, "s", &range, ValueRenderOption::Formatted).unwrap();
            assert!(
                url.as_str().contains(encoded),
                "{title:?} must encode to {encoded}: {url}"
            );
            assert!(url.fragment().is_none(), "{title:?} leaked a fragment");
            assert!(url.query().is_some_and(|q| !q.contains("!A1")));
            // The range must remain ONE path segment: /v4/spreadsheets/s/
            // values/<range> is exactly five.
            let segments: Vec<&str> = url.path_segments().unwrap().collect();
            assert_eq!(segments.len(), 5, "{title:?} split the path: {url}");
            assert_eq!(segments[3], "values", "{title:?} shifted the path: {url}");
        }
    }

    #[test]
    fn values_get_url_round_trips_the_range_through_decoding() {
        let range = "'Bob''s Sheet'!A1:C9";
        let url = build_values_get_url(BASE, "s", range, ValueRenderOption::Formatted).unwrap();
        let decoded = url
            .path_segments()
            .unwrap()
            .next_back()
            .map(percent_decode)
            .unwrap();
        assert_eq!(decoded, range);
    }

    fn percent_decode(segment: &str) -> String {
        percent_encoding::percent_decode_str(segment)
            .decode_utf8()
            .unwrap()
            .to_string()
    }

    #[test]
    fn values_get_url_sends_the_render_option() {
        for (render, wire) in [
            (ValueRenderOption::Formatted, "FORMATTED_VALUE"),
            (ValueRenderOption::Unformatted, "UNFORMATTED_VALUE"),
            (ValueRenderOption::Formula, "FORMULA"),
        ] {
            let url = build_values_get_url(BASE, "s", "A1", render).unwrap();
            let got = url
                .query_pairs()
                .find(|(k, _)| k == "valueRenderOption")
                .map(|(_, v)| v.to_string())
                .unwrap();
            assert_eq!(got, wire);
        }
    }

    // ── values.batchGet ────────────────────────────────────────────────

    #[test]
    fn batch_get_url_repeats_the_ranges_parameter() {
        let ranges = vec!["'A'!A1:B2".to_string(), "'B'!A1".to_string()];
        let url =
            build_values_batch_get_url(BASE, "s", &ranges, ValueRenderOption::Formatted).unwrap();
        assert_eq!(url.path(), "/v4/spreadsheets/s/values:batchGet");
        let got: Vec<String> = url
            .query_pairs()
            .filter(|(k, _)| k == "ranges")
            .map(|(_, v)| v.to_string())
            .collect();
        assert_eq!(got, ranges);
    }

    #[test]
    fn batch_get_url_keeps_the_colon_suffix_unencoded() {
        let url = build_values_batch_get_url(
            BASE,
            "s",
            &["A1".to_string()],
            ValueRenderOption::Formatted,
        )
        .unwrap();
        assert!(
            url.as_str().contains("/values:batchGet?"),
            "the :batchGet suffix must survive path encoding: {url}"
        );
    }

    #[test]
    fn batch_get_url_rejects_an_empty_range_list() {
        let err =
            build_values_batch_get_url(BASE, "s", &[], ValueRenderOption::Formatted).unwrap_err();
        assert!(err.to_string().contains("at least one range"), "{err}");
    }

    #[test]
    fn batch_get_url_rejects_more_ranges_than_the_cap() {
        let ranges: Vec<String> = (0..=MAX_RANGES_PER_BATCH)
            .map(|i| format!("S{i}"))
            .collect();
        let err = build_values_batch_get_url(BASE, "s", &ranges, ValueRenderOption::Formatted)
            .unwrap_err();
        assert!(err.to_string().contains("per-request cap"), "{err}");
    }

    // ── values.update / values.append / values.clear ──────────────────

    #[test]
    fn update_url_sends_the_value_input_option() {
        let url =
            build_values_update_url(BASE, "s", "A1:B2", ValueInputOption::UserEntered).unwrap();
        assert_eq!(url.path(), "/v4/spreadsheets/s/values/A1:B2");
        let input = url
            .query_pairs()
            .find(|(k, _)| k == "valueInputOption")
            .map(|(_, v)| v.to_string());
        assert_eq!(input, Some("USER_ENTERED".to_string()));
    }

    #[test]
    fn update_url_percent_encodes_a_quoted_sheet_title() {
        let url =
            build_values_update_url(BASE, "s", "'My Sheet'!A1", ValueInputOption::Raw).unwrap();
        assert!(url.path().contains("'My%20Sheet'"), "{url}");
    }

    #[test]
    fn append_url_keeps_the_colon_suffix_and_sets_insert_rows() {
        let url =
            build_values_append_url(BASE, "s", "A1:B2", ValueInputOption::UserEntered).unwrap();
        assert!(url.as_str().contains("/values/A1:B2:append"), "{url}");
        let insert_data_option = url
            .query_pairs()
            .find(|(k, _)| k == "insertDataOption")
            .map(|(_, v)| v.to_string());
        assert_eq!(insert_data_option, Some("INSERT_ROWS".to_string()));
        let input = url
            .query_pairs()
            .find(|(k, _)| k == "valueInputOption")
            .map(|(_, v)| v.to_string());
        assert_eq!(input, Some("USER_ENTERED".to_string()));
    }

    #[test]
    fn clear_url_keeps_the_colon_suffix_and_sends_no_query() {
        let url = build_values_clear_url(BASE, "s", "A1:B2").unwrap();
        assert!(url.as_str().contains("/values/A1:B2:clear"), "{url}");
        assert!(url.query().is_none(), "{url}");
    }

    // ── spreadsheets.sheets.copyTo ─────────────────────────────────────

    #[test]
    fn copy_to_url_keeps_the_colon_suffix_on_the_sheet_id_segment() {
        let url = build_copy_to_url(BASE, "dest-or-source-id", 12345).unwrap();
        assert_eq!(
            url.path(),
            "/v4/spreadsheets/dest-or-source-id/sheets/12345:copyTo"
        );
        assert!(url.query().is_none(), "{url}");
    }

    // ── batchUpdate reply handling (issue #2021) ───────────────────────

    /// A `SheetsApi` backed by `server`, with the OAuth token endpoint mounted.
    async fn sheets_client_for(server: &wiremock::MockServer) -> SheetsClient {
        use crate::drive::auth::{DriveCredentials, DriveGrantedScopes};
        use crate::drive::client::DriveClient;
        use crate::drive::sheets::client::SHEETS_API_URL;
        use crate::test_support::env::MapEnv;
        use crate::utils::secret::Secret;

        wiremock::Mock::given(wiremock::matchers::method("POST"))
            .and(wiremock::matchers::path("/token"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "access_token": "test-token", "expires_in": 3600,
                })),
            )
            .mount(server)
            .await;
        let credentials = DriveCredentials {
            client_id: "client-1".to_string(),
            client_secret: Secret::new("secret-1"),
            refresh_token: Secret::new("refresh-1"),
            scope: DriveGrantedScopes::READONLY,
        };
        let mut drive = DriveClient::new(&server.uri(), &credentials).unwrap();
        crate::drive::client::test_support::replace_session(
            &mut drive,
            &credentials,
            &format!("{}/token", server.uri()),
        );
        let env = MapEnv::new().with(SHEETS_API_URL, &server.uri());
        SheetsClient::from_drive_client_with(&env, &drive).unwrap()
    }

    /// Mounts a `batchUpdate` answering with `template`, expecting one call.
    async fn mount_batch_update_reply(
        server: &wiremock::MockServer,
        template: wiremock::ResponseTemplate,
    ) {
        wiremock::Mock::given(wiremock::matchers::method("POST"))
            .and(wiremock::matchers::path(
                "/v4/spreadsheets/sheet-1:batchUpdate",
            ))
            .respond_with(template)
            .expect(1)
            .mount(server)
            .await;
    }

    fn one_request() -> Vec<BatchUpdateRequestItem> {
        vec![BatchUpdateRequestItem::DeleteEmbeddedObject(
            crate::drive::sheets::types::DeleteEmbeddedObjectRequest { object_id: 1 },
        )]
    }

    #[tokio::test]
    async fn batch_update_parses_a_well_formed_2xx_reply_as_applied() {
        let server = wiremock::MockServer::start().await;
        let sheets = sheets_client_for(&server).await;
        mount_batch_update_reply(
            &server,
            wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "spreadsheetId": "sheet-1",
                "replies": [{"addChart": {"chart": {"chartId": 42}}}],
            })),
        )
        .await;

        let outcome = SheetsApi::new(&sheets)
            .batch_update("sheet-1", one_request())
            .await
            .unwrap();
        assert!(
            matches!(outcome, BatchUpdateOutcome::Applied(_)),
            "{outcome:?}"
        );
    }

    #[tokio::test]
    async fn batch_update_reports_a_2xx_with_a_non_json_body_as_applied_reply_unreadable() {
        let server = wiremock::MockServer::start().await;
        let sheets = sheets_client_for(&server).await;
        mount_batch_update_reply(
            &server,
            wiremock::ResponseTemplate::new(200).set_body_string("not json"),
        )
        .await;

        let outcome = SheetsApi::new(&sheets)
            .batch_update("sheet-1", one_request())
            .await
            .unwrap();
        let BatchUpdateOutcome::AppliedReplyUnreadable { detail } = outcome else {
            panic!("expected AppliedReplyUnreadable, got {outcome:?}"); // omni-dev: coverage ignore-line reason="the assertion arm only fires if the outcome type regresses, in which case the test has already failed"
        };
        assert!(
            detail.contains("Failed to parse Sheets batchUpdate response"),
            "{detail}"
        );
    }

    #[tokio::test]
    async fn batch_update_reports_a_2xx_with_a_mistyped_reply_as_applied_reply_unreadable() {
        let server = wiremock::MockServer::start().await;
        let sheets = sheets_client_for(&server).await;
        // `chartId` is an integer on the wire; a string is a reply-shape gap
        // of exactly the kind #1929 fixed one instance of.
        mount_batch_update_reply(
            &server,
            wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "replies": [{"addChart": {"chart": {"chartId": "x"}}}],
            })),
        )
        .await;

        let outcome = SheetsApi::new(&sheets)
            .batch_update("sheet-1", one_request())
            .await
            .unwrap();
        assert!(
            matches!(outcome, BatchUpdateOutcome::AppliedReplyUnreadable { .. }),
            "{outcome:?}"
        );
    }

    #[tokio::test]
    async fn batch_update_reports_a_2xx_with_an_empty_body_as_applied_reply_unreadable() {
        let server = wiremock::MockServer::start().await;
        let sheets = sheets_client_for(&server).await;
        mount_batch_update_reply(&server, wiremock::ResponseTemplate::new(200)).await;

        let outcome = SheetsApi::new(&sheets)
            .batch_update("sheet-1", one_request())
            .await
            .unwrap();
        assert!(
            matches!(outcome, BatchUpdateOutcome::AppliedReplyUnreadable { .. }),
            "{outcome:?}"
        );
    }

    #[tokio::test]
    async fn batch_update_reports_a_non_2xx_as_an_error_not_applied() {
        let server = wiremock::MockServer::start().await;
        let sheets = sheets_client_for(&server).await;
        mount_batch_update_reply(
            &server,
            wiremock::ResponseTemplate::new(403).set_body_json(serde_json::json!({
                "error": {
                    "code": 403,
                    "message": "The caller does not have permission",
                    "status": "PERMISSION_DENIED",
                }
            })),
        )
        .await;

        let err = SheetsApi::new(&sheets)
            .batch_update("sheet-1", one_request())
            .await
            .unwrap_err();
        let message = format!("{err:#}");
        assert!(message.contains("PERMISSION_DENIED"), "{message}");
        assert!(message.contains("--write-full"), "{message}");
    }

    #[test]
    fn applied_reply_unreadable_line_words_each_retry_hint() {
        assert_eq!(
            applied_reply_unreadable_line(
                "add chart",
                "'Budget'",
                RetryHint::NotIdempotent,
                "bad reply"
            ),
            "Applied, but the reply could not be read: add chart in 'Budget' — \
             do not retry; check the spreadsheet first (bad reply)"
        );
        assert_eq!(
            applied_reply_unreadable_line("sort A1:B2", "'Budget'", RetryHint::Idempotent, "x"),
            "Applied, but the reply could not be read: sort A1:B2 in 'Budget' — \
             check the spreadsheet to confirm (x)"
        );
    }

    /// Every engine that calls `batch_update` must name [`BatchUpdateOutcome`].
    ///
    /// The compiler only forces this where the engine reads the reply: an
    /// engine that matches `Ok(_)` compiles unchanged and would report an
    /// applied-but-unreadable reply as a plain `Changed` with no signal. The
    /// same grep-guard idiom keeps other cross-cutting rules honest.
    #[test]
    fn every_batch_update_caller_handles_an_unreadable_reply() {
        let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/drive");
        let mut files = Vec::new();
        let mut dirs = vec![root.join("sheets"), root.join("lease")];
        while let Some(dir) = dirs.pop() {
            for entry in std::fs::read_dir(&dir).unwrap() {
                let path = entry.unwrap().path();
                if path.is_dir() {
                    dirs.push(path);
                } else if path.extension().is_some_and(|e| e == "rs") {
                    files.push(path);
                }
            }
        }
        let mut callers = Vec::new();
        for path in files {
            let source = std::fs::read_to_string(&path).unwrap();
            // Only production code: everything before the `#[cfg(test)]`
            // that gates the trailing `mod tests`, so an earlier
            // cfg-gated item cannot hide the code after it.
            let production = source.rfind("\nmod tests").map_or(source.as_str(), |at| {
                source[..at]
                    .rfind("#[cfg(test)]")
                    .map_or(&source[..at], |cfg| &source[..cfg])
            });
            if production.contains(".batch_update(") {
                // The qualified path, not the bare identifier: an import or
                // a comment naming the variant must not satisfy the guard.
                callers.push((
                    path,
                    production.contains("BatchUpdateOutcome::AppliedReplyUnreadable"),
                ));
            }
        }
        assert!(
            callers.len() >= 21,
            "expected 21 callers, found {callers:?}"
        );
        let unhandled: Vec<_> = callers
            .iter()
            .filter(|(_, handled)| !handled)
            .map(|(path, _)| path.display().to_string())
            .collect();
        assert!(
            unhandled.is_empty(),
            "these batch_update callers never handle AppliedReplyUnreadable: {unhandled:?}"
        );
    }

    // ── base URL handling ──────────────────────────────────────────────

    #[test]
    fn urls_respect_a_wiremock_style_base_with_a_port() {
        let url = build_values_get_url(
            "http://127.0.0.1:9123",
            "s",
            "'My Sheet'!A1",
            ValueRenderOption::Formatted,
        )
        .unwrap();
        assert_eq!(url.host_str(), Some("127.0.0.1"));
        assert_eq!(url.port(), Some(9123));
        assert!(url.path().starts_with("/v4/spreadsheets/s/values/"));
    }

    #[test]
    fn render_option_default_is_formatted() {
        assert_eq!(ValueRenderOption::default(), ValueRenderOption::Formatted);
    }
}