alef-e2e 0.16.39

Fixture-driven e2e test generator for alef
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
//! Shared streaming-virtual-fields module for e2e test codegen.
//!
//! Chat-stream fixtures assert on "virtual" fields that don't exist on the
//! stream result type itself — `chunks`, `chunks.length`, `stream_content`,
//! `stream_complete`, `no_chunks_after_done`, `tool_calls`, `finish_reason`.
//! These fields resolve against the *collected* list of chunks produced by
//! draining the stream.
//!
//! [`StreamingFieldResolver`] provides two entry points:
//! - [`StreamingFieldResolver::accessor`] — the language-specific expression
//!   for a virtual field given a local variable that holds the collected list.
//! - [`StreamingFieldResolver::collect_snippet`] — the language-specific
//!   code snippet that drains a stream variable into the collected list.
//!
//! ## Convention
//!
//! The `chunks_var` parameter is the local variable name that holds the
//! collected list (default: `"chunks"`).  The `stream_var` parameter is the
//! result variable produced by the stream call (default: `"result"`).
//!
//! The set of streaming-virtual field names handled by this module:
//! - `chunks`              → the collected list itself
//! - `chunks.length`       → length/count of the collected list
//! - `stream_content`      → concatenation of all delta content strings
//! - `stream_complete`     → boolean — last chunk has a non-null finish_reason
//! - `no_chunks_after_done` → structural invariant (true by construction for
//!   channel/iterator-based APIs once the channel is closed; emitted as
//!   `assert!(true)` / `assertTrue` for languages without post-DONE chunk plumbing)
//! - `tool_calls`          → flat list of tool_calls from all chunk deltas
//! - `finish_reason`       → finish_reason string from the last chunk

/// The set of field names treated as streaming-virtual fields.
pub const STREAMING_VIRTUAL_FIELDS: &[&str] = &[
    "chunks",
    "chunks.length",
    "stream_content",
    "stream_complete",
    "no_chunks_after_done",
    "tool_calls",
    "finish_reason",
];

/// The set of streaming-virtual root names that may have deep-path continuations.
///
/// A field like `tool_calls[0].function.name` starts with `tool_calls` and has
/// a continuation `[0].function.name`. These are handled by
/// [`StreamingFieldResolver::accessor`] via the deep-path logic.
///
/// `usage` is a stream-level root: `usage.total_tokens` resolves against the
/// last chunk that carried a usage payload (accessed via the collected chunks
/// list). Python accessor: `(chunks[-1].usage if chunks else None)`.
const STREAMING_VIRTUAL_ROOTS: &[&str] = &["tool_calls", "finish_reason"];

/// Returns `true` when `field` is a streaming-virtual field name, including
/// deep-nested paths that start with a known streaming-virtual root.
///
/// Examples that return `true`:
/// - `"tool_calls"` (exact root)
/// - `"tool_calls[0].function.name"` (deep path)
/// - `"tool_calls[0].id"` (deep path)
pub fn is_streaming_virtual_field(field: &str) -> bool {
    if STREAMING_VIRTUAL_FIELDS.contains(&field) {
        return true;
    }
    // Check deep-path prefixes: `tool_calls[…` or `tool_calls.`
    for root in STREAMING_VIRTUAL_ROOTS {
        if field.len() > root.len() && field.starts_with(root) {
            let rest = &field[root.len()..];
            if rest.starts_with('[') || rest.starts_with('.') {
                return true;
            }
        }
    }
    false
}

/// Split a field path into `(root, tail)` when it starts with a streaming-virtual
/// root and has a continuation.
///
/// Returns `None` when the field is an exact root match (no tail) or is not a
/// streaming-virtual root at all.
fn split_streaming_deep_path(field: &str) -> Option<(&str, &str)> {
    for root in STREAMING_VIRTUAL_ROOTS {
        if field.len() > root.len() && field.starts_with(root) {
            let rest = &field[root.len()..];
            if rest.starts_with('[') || rest.starts_with('.') {
                return Some((root, rest));
            }
        }
    }
    None
}

/// Field names that unambiguously imply a streaming test (no overlap with
/// non-streaming response shapes). `usage`, `tool_calls`, and `finish_reason`
/// are intentionally excluded — they exist on non-streaming responses too
/// (`usage.total_tokens` on ChatCompletionResponse, `choices[0].finish_reason`,
/// etc.) and would otherwise drag non-streaming fixtures into streaming
/// codegen.
const STREAMING_ONLY_AUTO_DETECT_FIELDS: &[&str] = &[
    "chunks",
    "chunks.length",
    "stream_content",
    "stream_complete",
    "no_chunks_after_done",
];

/// Resolve whether a fixture should be treated as streaming, honoring the
/// call-level three-valued opt-in/out (`CallConfig::streaming`):
///
/// - `Some(true)` → forced streaming.
/// - `Some(false)` → forced non-streaming (skip the auto-detect even when an
///   assertion references a streaming-virtual-field name like `chunks`).
/// - `None` → auto-detect: streaming iff the fixture has a streaming mock
///   (`mock_response.stream_chunks`) or any assertion references one of the
///   unambiguous streaming-only field names.
///
/// All backends should use this helper so the opt-out is respected uniformly.
pub fn resolve_is_streaming(fixture: &crate::fixture::Fixture, call_streaming: Option<bool>) -> bool {
    if let Some(forced) = call_streaming {
        return forced;
    }
    fixture.is_streaming_mock()
        || fixture.assertions.iter().any(|a| {
            a.field
                .as_deref()
                .is_some_and(|f| !f.is_empty() && STREAMING_ONLY_AUTO_DETECT_FIELDS.contains(&f))
        })
}

/// Shared streaming-virtual-fields resolver for e2e test codegen.
pub struct StreamingFieldResolver;

impl StreamingFieldResolver {
    /// Returns the language-specific expression for a streaming-virtual field,
    /// given `chunks_var` (the collected-list local name) and `lang`.
    ///
    /// Returns `None` when the field name is not a known streaming-virtual
    /// field or the language has no streaming support.
    pub fn accessor(field: &str, lang: &str, chunks_var: &str) -> Option<String> {
        match field {
            "chunks" => Some(match lang {
                // Zig ArrayList does not expose .len directly; must use .items
                "zig" => format!("{chunks_var}.items"),
                // PHP variables require `$` sigil — bareword `chunks` is parsed as a
                // constant reference and triggers "Undefined constant" errors.
                "php" => format!("${chunks_var}"),
                _ => chunks_var.to_string(),
            }),

            "chunks.length" => Some(match lang {
                "rust" => format!("{chunks_var}.len()"),
                "go" => format!("len({chunks_var})"),
                "python" => format!("len({chunks_var})"),
                "php" => format!("count(${chunks_var})"),
                "elixir" => format!("length({chunks_var})"),
                // kotlin List.size is a property (not .length)
                "kotlin" => format!("{chunks_var}.size"),
                // zig: chunks_var is ArrayList([]u8); use .items.len
                "zig" => format!("{chunks_var}.items.len"),
                // Swift Array uses .count (Collection protocol)
                "swift" => format!("{chunks_var}.count"),
                // node/wasm/typescript use .length
                _ => format!("{chunks_var}.length"),
            }),

            "stream_content" => Some(match lang {
                "rust" => {
                    format!(
                        "{chunks_var}.iter().map(|c| c.choices.first().and_then(|ch| ch.delta.content.as_deref()).unwrap_or(\"\")).collect::<String>()"
                    )
                }
                "go" => {
                    // Go: chunks is []pkg.ChatCompletionChunk
                    format!(
                        "func() string {{ var s string; for _, c := range {chunks_var} {{ if len(c.Choices) > 0 && c.Choices[0].Delta.Content != nil {{ s += *c.Choices[0].Delta.Content }} }}; return s }}()"
                    )
                }
                "java" => {
                    format!(
                        "{chunks_var}.stream().map(c -> c.choices().stream().findFirst().map(ch -> ch.delta().content() != null ? ch.delta().content() : \"\").orElse(\"\")).collect(java.util.stream.Collectors.joining())"
                    )
                }
                "php" => {
                    format!("implode('', array_map(fn($c) => $c->choices[0]->delta->content ?? '', ${chunks_var}))")
                }
                "kotlin" => {
                    // Kotlin: chunks is List<ChatCompletionChunk> (Java records via typealias).
                    // choices() / delta() / content() are Java record accessor methods.
                    format!(
                        "{chunks_var}.joinToString(\"\") {{ it.choices()?.firstOrNull()?.delta()?.content() ?: \"\" }}"
                    )
                }
                "kotlin_android" => {
                    // kotlin-android: data classes use Kotlin property access (no parens).
                    format!("{chunks_var}.joinToString(\"\") {{ it.choices?.firstOrNull()?.delta?.content ?: \"\" }}")
                }
                "elixir" => {
                    // StreamDelta has all fields optional with skip_serializing_if, so
                    // absent fields are not present as keys in the Jason-decoded map.
                    // Use Map.get with defaults to avoid KeyError on absent :content.
                    format!(
                        "{chunks_var} |> Enum.map(fn c -> (Enum.at(c.choices, 0) || %{{}}) |> Map.get(:delta, %{{}}) |> Map.get(:content, \"\") end) |> Enum.join(\"\")"
                    )
                }
                "python" => {
                    format!("\"\".join(c.choices[0].delta.content or \"\" for c in {chunks_var} if c.choices)")
                }
                "zig" => {
                    // Zig: `{chunks_var}_content` is a `std.ArrayList(u8)` populated by
                    // the collect snippet. `.items` gives a `[]u8` slice of the content.
                    format!("{chunks_var}_content.items")
                }
                // Swift: chunks is [ChatCompletionChunk] (swift-bridge class objects).
                // choices() → RustVec<StreamChoice> (Collection, so .first is available).
                // delta() → StreamDelta (non-optional). content() → RustString? → .toString().
                "swift" => {
                    format!(
                        "{chunks_var}.map {{ c in c.choices().first.flatMap {{ ch in ch.delta().content()?.toString() }} ?? \"\" }}.joined()"
                    )
                }
                // node/wasm/typescript
                _ => {
                    format!("{chunks_var}.map((c: any) => c.choices?.[0]?.delta?.content ?? '').join('')")
                }
            }),

            "stream_complete" => Some(match lang {
                "rust" => {
                    format!(
                        "{chunks_var}.last().and_then(|c| c.choices.first()).and_then(|ch| ch.finish_reason.as_ref()).is_some()"
                    )
                }
                "go" => {
                    format!(
                        "func() bool {{ if len({chunks_var}) == 0 {{ return false }}; last := {chunks_var}[len({chunks_var})-1]; return len(last.Choices) > 0 && last.Choices[0].FinishReason != nil }}()"
                    )
                }
                "java" => {
                    format!(
                        "!{chunks_var}.isEmpty() && {chunks_var}.get({chunks_var}.size()-1).choices().stream().findFirst().flatMap(ch -> java.util.Optional.ofNullable(ch.finishReason())).isPresent()"
                    )
                }
                "php" => {
                    // PHP streaming chunks come from `json_decode` of the binding's JSON
                    // string return. The PHP binding serializes with rename_all = "camelCase",
                    // so use `finishReason` (camelCase) to match the emitted JSON keys.
                    format!("!empty(${chunks_var}) && isset(end(${chunks_var})->choices[0]->finishReason)")
                }
                "kotlin" => {
                    // Kotlin: use isNotEmpty() + last() + safe-call chain
                    format!(
                        "{chunks_var}.isNotEmpty() && {chunks_var}.last().choices()?.firstOrNull()?.finishReason() != null"
                    )
                }
                "kotlin_android" => {
                    // kotlin-android: data classes use Kotlin property access (no parens).
                    format!(
                        "{chunks_var}.isNotEmpty() && {chunks_var}.last().choices?.firstOrNull()?.finishReason != null"
                    )
                }
                "python" => {
                    format!("bool({chunks_var}) and {chunks_var}[-1].choices[0].finish_reason is not None")
                }
                "elixir" => {
                    format!("Enum.at(List.last({chunks_var}).choices, 0).finish_reason != nil")
                }
                // zig: the collect snippet exhausts the stream; check last chunk JSON
                // was collected (chunks.items is non-empty) as a proxy for completion.
                "zig" => {
                    format!("{chunks_var}.items.len > 0")
                }
                // Swift: chunks is [ChatCompletionChunk] (swift-bridge class objects).
                // choices() → RustVec<StreamChoice> (Collection), .first is Optional.
                // finish_reason() → RustString? (non-nil when the stream completed).
                "swift" => {
                    format!("!{chunks_var}.isEmpty && {chunks_var}.last!.choices().first?.finish_reason() != nil")
                }
                // node/wasm/typescript
                _ => {
                    format!(
                        "{chunks_var}.length > 0 && {chunks_var}[{chunks_var}.length - 1].choices?.[0]?.finishReason != null"
                    )
                }
            }),

            // no_chunks_after_done is a structural invariant: once the stream
            // closes (channel drained / iterator exhausted), no further chunks
            // can arrive.  We assert `true` as a compile-time proof of intent.
            "no_chunks_after_done" => Some(match lang {
                "rust" => "true".to_string(),
                "go" => "true".to_string(),
                "java" => "true".to_string(),
                "php" => "true".to_string(),
                _ => "true".to_string(),
            }),

            "tool_calls" => Some(match lang {
                "rust" => {
                    format!(
                        "{chunks_var}.iter().flat_map(|c| c.choices.iter().flat_map(|ch| ch.delta.tool_calls.iter().flatten())).collect::<Vec<_>>()"
                    )
                }
                "go" => {
                    // StreamDelta.ToolCalls is `[]StreamToolCall` (slice, not pointer).
                    // Return the typed slice so deep-path accessors like `tool_calls[0].function.name`
                    // can index and access typed fields.
                    format!(
                        "func() []pkg.StreamToolCall {{ var tc []pkg.StreamToolCall; for _, c := range {chunks_var} {{ for _, ch := range c.Choices {{ tc = append(tc, ch.Delta.ToolCalls...) }} }}; return tc }}()"
                    )
                }
                "java" => {
                    format!(
                        "{chunks_var}.stream().flatMap(c -> c.choices().stream()).flatMap(ch -> ch.delta().toolCalls() != null ? ch.delta().toolCalls().stream() : java.util.stream.Stream.empty()).toList()"
                    )
                }
                "php" => {
                    // PHP streaming chunks are json_decoded stdClass. The PHP binding
                    // serializes with rename_all = "camelCase", so use `toolCalls`.
                    format!(
                        "array_merge(...array_map(fn($c) => $c->choices[0]->delta->toolCalls ?? [], ${chunks_var}))"
                    )
                }
                "kotlin" => {
                    // Kotlin: flatten tool_calls from all chunk deltas into one list
                    format!(
                        "{chunks_var}.flatMap {{ c -> c.choices()?.flatMap {{ ch -> ch.delta()?.toolCalls() ?: emptyList() }} ?: emptyList() }}"
                    )
                }
                "kotlin_android" => {
                    // kotlin-android: data classes use Kotlin property access (no parens).
                    format!(
                        "{chunks_var}.flatMap {{ c -> c.choices?.flatMap {{ ch -> ch.delta?.toolCalls ?: emptyList() }} ?: emptyList() }}"
                    )
                }
                "python" => {
                    format!(
                        "[t for c in {chunks_var} for ch in (c.choices or []) for t in (ch.delta.tool_calls or [])]"
                    )
                }
                "elixir" => {
                    format!(
                        "{chunks_var} |> Enum.flat_map(fn c -> (List.first(c.choices) || %{{}}).delta |> Map.get(:tool_calls, []) end)"
                    )
                }
                // Zig: tool_calls count from all chunk deltas
                "zig" => {
                    format!("{chunks_var}.items")
                }
                // Swift: chunks is [ChatCompletionChunk] (swift-bridge class objects).
                // choices() → RustVec<StreamChoice> (Collection). delta() → StreamDelta.
                // tool_calls() → RustVec<StreamToolCall>?
                // Use an explicit return type annotation on the outer closure so Swift's
                // type checker doesn't pick the Optional overload of flatMap.  Guard-let
                // unwrapping avoids ambiguous ?? operator precedence.
                "swift" => {
                    format!(
                        "{chunks_var}.flatMap {{ c -> [StreamToolCallRef] in guard let ch = c.choices().first, let tcs = ch.delta().tool_calls() else {{ return [] }}; return Array(tcs) }}"
                    )
                }
                _ => {
                    format!("{chunks_var}.flatMap((c: any) => c.choices?.[0]?.delta?.toolCalls ?? [])")
                }
            }),

            "finish_reason" => Some(match lang {
                "rust" => {
                    // ChatCompletionChunk's finish_reason is Option<FinishReason> (enum, not
                    // String). Display impl writes the JSON wire form (e.g. "tool_calls").
                    format!(
                        "{chunks_var}.last().and_then(|c| c.choices.first()).and_then(|ch| ch.finish_reason.as_ref()).map(|v| v.to_string()).unwrap_or_default()"
                    )
                }
                "go" => {
                    // FinishReason is a typed alias (`type FinishReason string`) in bindings,
                    // so cast to string explicitly to match the assertion target type.
                    format!(
                        "func() string {{ if len({chunks_var}) == 0 {{ return \"\" }}; last := {chunks_var}[len({chunks_var})-1]; if len(last.Choices) > 0 && last.Choices[0].FinishReason != nil {{ return string(*last.Choices[0].FinishReason) }}; return \"\" }}()"
                    )
                }
                "java" => {
                    // FinishReason.getValue() returns the JSON wire string (e.g. "tool_calls").
                    // Without it, assertEquals(String, FinishReason) fails because Object.equals
                    // doesn't cross types even when toString() matches.
                    format!(
                        "({chunks_var}.isEmpty() ? null : {chunks_var}.get({chunks_var}.size()-1).choices().stream().findFirst().map(ch -> ch.finishReason() == null ? null : ch.finishReason().getValue()).orElse(null))"
                    )
                }
                "php" => {
                    // PHP streaming chunks are json_decoded stdClass. The PHP binding
                    // serializes with rename_all = "camelCase", so use `finishReason`.
                    format!("(!empty(${chunks_var}) ? (end(${chunks_var})->choices[0]->finishReason ?? null) : null)")
                }
                "kotlin" => {
                    // Returns the string value of the finish_reason enum from the last chunk.
                    // FinishReason.getValue() returns the JSON wire string (e.g. "tool_calls").
                    format!(
                        "(if ({chunks_var}.isEmpty()) null else {chunks_var}.last().choices()?.firstOrNull()?.finishReason()?.getValue())"
                    )
                }
                "kotlin_android" => {
                    // kotlin-android: plain Kotlin enum class uses .name.lowercase() for wire string.
                    format!(
                        "(if ({chunks_var}.isEmpty()) null else {chunks_var}.last().choices?.firstOrNull()?.finishReason?.name?.lowercase())"
                    )
                }
                "python" => {
                    // FinishReason is a PyO3 enum object, not a plain string.
                    // Wrap in str() so callers can do `.strip()` / string comparisons
                    // without `AttributeError: 'FinishReason' has no attribute 'strip'`.
                    format!(
                        "(str({chunks_var}[-1].choices[0].finish_reason) if {chunks_var} and {chunks_var}[-1].choices else None)"
                    )
                }
                "elixir" => {
                    format!("Enum.at(List.last({chunks_var}).choices, 0).finish_reason")
                }
                // Zig: finish_reason from the last chunk's JSON via an inline labeled block.
                // Returns `[]const u8` (unwrapped with orelse "" for expectEqualStrings).
                "zig" => {
                    format!(
                        "(blk: {{ if ({chunks_var}.items.len == 0) break :blk \"\"; var _lcp = std.json.parseFromSlice(std.json.Value, std.heap.c_allocator, {chunks_var}.items[{chunks_var}.items.len - 1], .{{}}) catch break :blk \"\"; defer _lcp.deinit(); if (_lcp.value.object.get(\"choices\")) |_lchs| if (_lchs.array.items.len > 0) if (_lchs.array.items[0].object.get(\"finish_reason\")) |_fr| if (_fr == .string) break :blk _fr.string; break :blk \"\"; }})"
                    )
                }
                // Swift: FinishReason is a swift-bridge opaque class with .to_string() → RustString.
                // finish_reason() on StreamChoiceRef returns RustString? (the raw wire string).
                // Return nil when chunks is empty or the last choice has no finish_reason.
                "swift" => {
                    format!(
                        "({chunks_var}.isEmpty ? nil : {chunks_var}.last!.choices().first?.finish_reason()?.toString())"
                    )
                }
                _ => {
                    format!(
                        "{chunks_var}.length > 0 ? {chunks_var}[{chunks_var}.length - 1].choices?.[0]?.finishReason : undefined"
                    )
                }
            }),

            // `usage` is a stream-level virtual root: resolves against the last
            // chunk that carried a usage payload.  Deep paths like `usage.total_tokens`
            // are handled by the deep-path logic in the `_` arm below (root=`usage`,
            // tail=`.total_tokens`), which calls this base accessor and appends the tail.
            "usage" => Some(match lang {
                "python" => {
                    // Access the last chunk's usage object (may be None).
                    // Deep paths like usage.total_tokens are rendered as:
                    //   (chunks[-1].usage if chunks else None).total_tokens
                    format!("({chunks_var}[-1].usage if {chunks_var} else None)")
                }
                "rust" => {
                    format!("{chunks_var}.last().and_then(|c| c.usage.as_ref())")
                }
                "go" => {
                    format!(
                        "func() interface{{}} {{ if len({chunks_var}) == 0 {{ return nil }}; return {chunks_var}[len({chunks_var})-1].Usage }}()"
                    )
                }
                "java" => {
                    format!("({chunks_var}.isEmpty() ? null : {chunks_var}.get({chunks_var}.size()-1).usage())")
                }
                "kotlin" => {
                    format!("(if ({chunks_var}.isEmpty()) null else {chunks_var}.last().usage())")
                }
                "kotlin_android" => {
                    // kotlin-android: data classes use Kotlin property access (no parens).
                    format!("(if ({chunks_var}.isEmpty()) null else {chunks_var}.last().usage)")
                }
                "php" => {
                    format!("(!empty(${chunks_var}) ? end(${chunks_var})->usage ?? null : null)")
                }
                "elixir" => {
                    format!("(if length({chunks_var}) > 0, do: List.last({chunks_var}).usage, else: nil)")
                }
                // Swift: usage() on ChatCompletionChunkRef returns Usage? (swift-bridge class).
                "swift" => {
                    format!("({chunks_var}.isEmpty ? nil : {chunks_var}.last!.usage())")
                }
                _ => {
                    format!("({chunks_var}.length > 0 ? {chunks_var}[{chunks_var}.length - 1].usage : undefined)")
                }
            }),

            _ => {
                // Deep-path: e.g. `tool_calls[0].function.name`
                // Split into root + tail, get the root's inline expression, then
                // render the tail (index + fields) in a per-language style on top.
                if let Some((root, tail)) = split_streaming_deep_path(field) {
                    // Rust needs Option-aware chaining for the StreamToolCall fields
                    // (function/id are Option<...>). The generic tail renderer can't
                    // infer Option-wrapping, so we emit rust-specific idiom here.
                    if lang == "rust" && root == "tool_calls" {
                        return Some(render_rust_tool_calls_deep(chunks_var, tail));
                    }
                    // Swift: StreamToolCallRef fields are swift-bridge methods returning
                    // Optional.  The generic render_deep_tail doesn't know to add `()`
                    // or optional-chain with `?.`, so use a dedicated renderer.
                    if lang == "swift" && root == "tool_calls" {
                        let root_expr = Self::accessor(root, lang, chunks_var)?;
                        return Some(render_swift_tool_calls_deep(&root_expr, tail));
                    }
                    // Zig stores stream chunks as JSON strings (`[]const u8`) in
                    // `chunks: ArrayList([]u8)`, not typed `ChatCompletionChunk`
                    // records. A deep `tool_calls[N].function.name` access would
                    // require parsing each chunk's JSON inline — rather than
                    // emit code that won't compile, signal "unsupported" so the
                    // assertion is skipped at the call site.
                    if lang == "zig" && root == "tool_calls" {
                        return None;
                    }
                    let root_expr = Self::accessor(root, lang, chunks_var)?;
                    Some(render_deep_tail(&root_expr, tail, lang))
                } else {
                    None
                }
            }
        }
    }

    /// Returns the language-specific stream-collect-into-list snippet that
    /// produces `chunks_var` from `stream_var`.
    ///
    /// Returns `None` when the language has no streaming collect support or
    /// when the collect snippet cannot be expressed generically.
    pub fn collect_snippet(lang: &str, stream_var: &str, chunks_var: &str) -> Option<String> {
        match lang {
            "rust" => Some(format!(
                "let {chunks_var}: Vec<_> = tokio_stream::StreamExt::collect::<Vec<_>>({stream_var}).await\n        .into_iter()\n        .map(|r| r.expect(\"stream item failed\"))\n        .collect();"
            )),
            "go" => Some(format!(
                "var {chunks_var} []pkg.ChatCompletionChunk\n\tfor chunk := range {stream_var} {{\n\t\t{chunks_var} = append({chunks_var}, chunk)\n\t}}"
            )),
            "java" => Some(format!(
                "var {chunks_var} = new java.util.ArrayList<ChatCompletionChunk>();\n        var _it = {stream_var}.iterator();\n        while (_it.hasNext()) {{ {chunks_var}.add(_it.next()); }}"
            )),
            // PHP binding's chat_stream_async typically returns a JSON string of the
            // chunk array (PHP cannot expose Rust iterators directly via ext-php-rs).
            // Decode to an array of stdClass objects so accessor chains like
            // `$c->choices[0]->delta->content` resolve against the JSON wire shape
            // (snake_case keys).  Falls back to iterator_to_array for a future binding
            // upgrade that exposes a real iterator.
            "php" => Some(format!(
                "${chunks_var} = is_string(${stream_var}) ? (json_decode(${stream_var}) ?: []) : iterator_to_array(${stream_var});"
            )),
            "python" => Some(format!(
                "{chunks_var} = []\n    async for chunk in {stream_var}:\n        {chunks_var}.append(chunk)"
            )),
            "kotlin" => {
                // Kotlin: chatStream returns Iterator<ChatCompletionChunk> (from Java bridge).
                // Drain into a Kotlin List using asSequence().toList().
                Some(format!("val {chunks_var} = {stream_var}.asSequence().toList()"))
            }
            "kotlin_android" => {
                // kotlin-android: chatStream returns Flow<ChatCompletionChunk> (kotlinx.coroutines).
                // Collect inside a runBlocking coroutine scope using Flow.toList().
                Some(format!("val {chunks_var} = {stream_var}.toList()"))
            }
            "elixir" => Some(format!("{chunks_var} = Enum.to_list({stream_var})")),
            "node" | "wasm" | "typescript" => Some(format!(
                "const {chunks_var}: any[] = [];\n    for await (const _chunk of {stream_var}) {{ {chunks_var}.push(_chunk); }}"
            )),
            "swift" => {
                // Swift's chat-stream wrapper returns AsyncThrowingStream<ChunkType, Error>,
                // so consumers drain it with `for try await chunk in stream { ... }`. The
                // chunk type is decoded from the bridge-boundary JSON inside the wrapper —
                // here we just collect the typed Swift values.
                Some(format!(
                    "var {chunks_var}: [ChatCompletionChunk] = []\n        for try await _chunk in {stream_var} {{ {chunks_var}.append(_chunk) }}"
                ))
            }
            "zig" => Some(Self::collect_snippet_zig(stream_var, chunks_var, "module", "ffi")),
            _ => None,
        }
    }

    /// Render Zig's streaming collect snippet using the configured module and FFI prefix.
    pub fn collect_snippet_zig(stream_var: &str, chunks_var: &str, module_name: &str, ffi_prefix: &str) -> String {
        let stream_next = format!("{ffi_prefix}_default_client_chat_stream_next");
        let chunk_to_json = format!("{ffi_prefix}_chat_completion_chunk_to_json");
        let chunk_free = format!("{ffi_prefix}_chat_completion_chunk_free");
        let free_string = format!("{ffi_prefix}_free_string");

        // Zig 0.16: ArrayList is unmanaged — no stored allocator.
        // Use `.empty` to initialize, pass `std.heap.c_allocator` to each mutation.
        // `stream_var` is the opaque stream handle obtained via `_start`.
        // We collect every chunk's JSON string into `chunks_var: ArrayList([]u8)`
        // and concatenate delta content into `{chunks_var}_content: ArrayList(u8)`.
        // Accessors use `.items.len` and `{chunks_var}_content.items` on these lists.
        format!(
            concat!(
                "var {chunks_var}: std.ArrayList([]u8) = .empty;
",
                "    defer {{
",
                "        for ({chunks_var}.items) |_cj| std.heap.c_allocator.free(_cj);
",
                "        {chunks_var}.deinit(std.heap.c_allocator);
",
                "    }}
",
                "    var {chunks_var}_content: std.ArrayList(u8) = .empty;
",
                "    defer {chunks_var}_content.deinit(std.heap.c_allocator);
",
                "    while (true) {{
",
                "        const _nc = {module_name}.c.{stream_next}({stream_var});
",
                "        if (_nc == null) break;
",
                "        const _np = {module_name}.c.{chunk_to_json}(_nc);
",
                "        {module_name}.c.{chunk_free}(_nc);
",
                "        if (_np == null) continue;
",
                "        const _ns = std.mem.span(_np);
",
                "        const _nj = try std.heap.c_allocator.dupe(u8, _ns);
",
                "        {module_name}.c.{free_string}(_np);
",
                "        if (std.json.parseFromSlice(std.json.Value, std.heap.c_allocator, _nj, .{{}})) |_cp| {{
",
                "            defer _cp.deinit();
",
                "            if (_cp.value.object.get(\"choices\")) |_chs|
",
                "                if (_chs.array.items.len > 0)
",
                "                    if (_chs.array.items[0].object.get(\"delta\")) |_dl|
",
                "                        if (_dl.object.get(\"content\")) |_ct|
",
                "                            if (_ct == .string) try {chunks_var}_content.appendSlice(std.heap.c_allocator, _ct.string);
",
                "        }} else |_| {{}}
",
                "        try {chunks_var}.append(std.heap.c_allocator, _nj);
",
                "    }}"
            ),
            chunks_var = chunks_var,
            stream_var = stream_var,
            module_name = module_name,
            stream_next = stream_next,
            chunk_to_json = chunk_to_json,
            chunk_free = chunk_free,
            free_string = free_string,
        )
    }
}

/// Render a Swift deep accessor for `tool_calls[N]...` paths.
///
/// The flat tool_calls array is `[StreamToolCallRef]`.  Each element is a
/// swift-bridge opaque ref: the first field after an index (e.g. `function`)
/// is accessed with `.method()` (direct call on the non-optional ref).
/// All subsequent fields use `?.method()` (optional chaining) because each
/// intermediate method returns `Optional`.  The string leaf appends
/// `?.toString()` to convert `RustString?` to `String?`.
///
/// Example: `[0].function.name`
///   → `(root)[0].function()?.name()?.toString()`
fn render_swift_tool_calls_deep(root_expr: &str, tail: &str) -> String {
    use heck::ToLowerCamelCase;
    let segs = parse_tail(tail);
    let mut expr = root_expr.to_string();
    let last_field_idx = segs.iter().rposition(|s| matches!(s, TailSeg::Field(_)));
    // Track whether the previous segment was an index (non-optional element),
    // which means the next field uses `.method()` not `?.method()`.
    let mut prev_was_index = false;

    for (i, seg) in segs.iter().enumerate() {
        match seg {
            TailSeg::Index(n) => {
                expr = format!("({expr})[{n}]");
                prev_was_index = true;
            }
            TailSeg::Field(f) => {
                let method = f.to_lower_camel_case();
                let is_last = Some(i) == last_field_idx;
                let chain = if prev_was_index { "." } else { "?." };
                if is_last {
                    // Leaf: string field — call + optional-chain .toString()
                    expr = format!("{expr}{chain}{method}()?.toString()");
                } else {
                    // Intermediate object field
                    expr = format!("{expr}{chain}{method}()");
                }
                prev_was_index = false;
            }
        }
    }
    expr
}

/// Render a rust deep accessor for `tool_calls[N]...` paths over the flattened
/// stream-chunk tool_calls iterator. Handles Option-wrapped fields by chaining
/// `as_ref().and_then(...)` so the final value is a `&str` (for name/id/arguments).
fn render_rust_tool_calls_deep(chunks_var: &str, tail: &str) -> String {
    let segs = parse_tail(tail);
    // Locate index segment (rust uses .nth(n) on the iterator instead of [N] on a Vec)
    let idx = segs.iter().find_map(|s| match s {
        TailSeg::Index(n) => Some(*n),
        _ => None,
    });
    let field_segs: Vec<&str> = segs
        .iter()
        .filter_map(|s| match s {
            TailSeg::Field(f) => Some(f.as_str()),
            _ => None,
        })
        .collect();

    let base = format!(
        "{chunks_var}.iter().flat_map(|c| c.choices.iter().flat_map(|ch| ch.delta.tool_calls.iter().flatten()))"
    );
    let with_nth = match idx {
        Some(n) => format!("{base}.nth({n})"),
        None => base,
    };

    // Chain Option-aware field access. Every field on StreamToolCall is Option<...>;
    // the leaf (String fields) uses `.as_deref()` to project to `&str`.
    let mut expr = with_nth;
    for (i, f) in field_segs.iter().enumerate() {
        let is_leaf = i == field_segs.len() - 1;
        if is_leaf {
            expr = format!("{expr}.and_then(|x| x.{f}.as_deref())");
        } else {
            expr = format!("{expr}.and_then(|x| x.{f}.as_ref())");
        }
    }
    format!("{expr}.unwrap_or(\"\")")
}

/// Parse a deep-path tail (e.g. `[0].function.name`) into structured segments.
///
/// The tail always starts with either `[N]` (array index) or `.field`.
/// Returns a list of segments: `TailSeg::Index(N)` or `TailSeg::Field(name)`.
#[derive(Debug, PartialEq)]
enum TailSeg {
    Index(usize),
    Field(String),
}

fn parse_tail(tail: &str) -> Vec<TailSeg> {
    let mut segs = Vec::new();
    let mut rest = tail;
    while !rest.is_empty() {
        if let Some(inner) = rest.strip_prefix('[') {
            // Array index: `[N]`
            if let Some(close) = inner.find(']') {
                let idx_str = &inner[..close];
                if let Ok(idx) = idx_str.parse::<usize>() {
                    segs.push(TailSeg::Index(idx));
                }
                rest = &inner[close + 1..];
            } else {
                break;
            }
        } else if let Some(inner) = rest.strip_prefix('.') {
            // Field name: up to next `.` or `[`
            let end = inner.find(['.', '[']).unwrap_or(inner.len());
            segs.push(TailSeg::Field(inner[..end].to_string()));
            rest = &inner[end..];
        } else {
            break;
        }
    }
    segs
}

/// Render the full deep accessor expression by appending per-language tail
/// segments onto `root_expr`.
fn render_deep_tail(root_expr: &str, tail: &str, lang: &str) -> String {
    use heck::{ToLowerCamelCase, ToPascalCase};

    let segs = parse_tail(tail);
    let mut out = root_expr.to_string();

    for seg in &segs {
        match (seg, lang) {
            (TailSeg::Index(n), "rust") => {
                out = format!("({out})[{n}]");
            }
            (TailSeg::Index(n), "java") => {
                out = format!("({out}).get({n})");
            }
            (TailSeg::Index(n), "kotlin") => {
                if *n == 0 {
                    out = format!("({out}).first()");
                } else {
                    out = format!("({out}).get({n})");
                }
            }
            (TailSeg::Index(n), "kotlin_android") => {
                if *n == 0 {
                    out = format!("({out}).first()");
                } else {
                    out = format!("({out})[{n}]");
                }
            }
            (TailSeg::Index(n), "elixir") => {
                out = format!("Enum.at({out}, {n})");
            }
            (TailSeg::Index(n), "zig") => {
                out = format!("({out}).items[{n}]");
            }
            (TailSeg::Index(n), "php") => {
                out = format!("({out})[{n}]");
            }
            (TailSeg::Index(n), _) => {
                // rust-like for go (but we handle Field differently), python, node, ts, kotlin, etc.
                out = format!("({out})[{n}]");
            }
            (TailSeg::Field(f), "rust") => {
                use heck::ToSnakeCase;
                out.push('.');
                out.push_str(&f.to_snake_case());
            }
            (TailSeg::Field(f), "go") => {
                use alef_codegen::naming::to_go_name;
                out.push('.');
                out.push_str(&to_go_name(f));
            }
            (TailSeg::Field(f), "java") => {
                out.push('.');
                out.push_str(&f.to_lower_camel_case());
                out.push_str("()");
            }
            (TailSeg::Field(f), "kotlin") => {
                // Use safe-call `?.` for all field accessors in Kotlin deep paths.
                // All streaming tool-call sub-fields (`function`, `id`, `name`,
                // `arguments`) are nullable in the generated Java records, so `?.`
                // is always correct here and prevents "non-null asserted call on
                // nullable receiver" compile errors.
                out.push_str("?.");
                out.push_str(&f.to_lower_camel_case());
                out.push_str("()");
            }
            (TailSeg::Field(f), "kotlin_android") => {
                // kotlin-android: Kotlin data classes use property access (no parens).
                out.push_str("?.");
                out.push_str(&f.to_lower_camel_case());
            }
            (TailSeg::Field(f), "csharp") => {
                out.push('.');
                out.push_str(&f.to_pascal_case());
            }
            (TailSeg::Field(f), "php") => {
                // Streaming PHP accessors operate on json_decoded stdClass with
                // snake_case property names (JSON wire format), not the camelCase
                // properties exposed on the PHP wrapper class. Use the raw field
                // name verbatim.
                out.push_str("->");
                out.push_str(f);
            }
            (TailSeg::Field(f), "elixir") => {
                out.push('.');
                out.push_str(f);
            }
            (TailSeg::Field(f), "zig") => {
                out.push('.');
                out.push_str(f);
            }
            (TailSeg::Field(f), "python") | (TailSeg::Field(f), "ruby") => {
                out.push('.');
                out.push_str(f);
            }
            // node, wasm, typescript, kotlin, dart, swift all use camelCase
            (TailSeg::Field(f), _) => {
                out.push('.');
                out.push_str(&f.to_lower_camel_case());
            }
        }
    }

    out
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn is_streaming_virtual_field_recognizes_all_fields() {
        for field in STREAMING_VIRTUAL_FIELDS {
            assert!(
                is_streaming_virtual_field(field),
                "field '{field}' not recognized as streaming virtual"
            );
        }
    }

    #[test]
    fn is_streaming_virtual_field_rejects_real_fields() {
        assert!(!is_streaming_virtual_field("content"));
        assert!(!is_streaming_virtual_field("choices"));
        assert!(!is_streaming_virtual_field("model"));
        assert!(!is_streaming_virtual_field(""));
    }

    #[test]
    fn is_streaming_virtual_field_rejects_non_root_paths_with_matching_tail() {
        // Regression: prior impl matched any field whose chars-after-root-len started
        // with `[` or `.` — without checking that the field actually starts with the
        // root token. `choices[0].finish_reason` therefore falsely matched root
        // `tool_calls` because byte 10 onward is `.finish_reason`.
        assert!(!is_streaming_virtual_field("choices[0].finish_reason"));
        assert!(!is_streaming_virtual_field("choices[0].message.content"));
        assert!(!is_streaming_virtual_field("data[0].embedding"));
    }

    #[test]
    fn is_streaming_virtual_field_does_not_match_usage() {
        // `usage` is intentionally NOT a streaming-virtual root: chat/embed
        // responses carry `usage.total_tokens` at the response root, so treating
        // it as virtual would drag non-streaming tests into the chunks accessor.
        assert!(!is_streaming_virtual_field("usage"));
        assert!(!is_streaming_virtual_field("usage.total_tokens"));
        assert!(!is_streaming_virtual_field("usage.prompt_tokens"));
    }

    #[test]
    fn accessor_chunks_returns_var_name() {
        assert_eq!(
            StreamingFieldResolver::accessor("chunks", "rust", "chunks"),
            Some("chunks".to_string())
        );
        assert_eq!(
            StreamingFieldResolver::accessor("chunks", "node", "chunks"),
            Some("chunks".to_string())
        );
    }

    #[test]
    fn accessor_chunks_length_uses_language_idiom() {
        let rust = StreamingFieldResolver::accessor("chunks.length", "rust", "chunks").unwrap();
        assert!(rust.contains(".len()"), "rust: {rust}");

        let go = StreamingFieldResolver::accessor("chunks.length", "go", "chunks").unwrap();
        assert!(go.starts_with("len("), "go: {go}");

        let node = StreamingFieldResolver::accessor("chunks.length", "node", "chunks").unwrap();
        assert!(node.contains(".length"), "node: {node}");

        let php = StreamingFieldResolver::accessor("chunks.length", "php", "chunks").unwrap();
        assert!(php.starts_with("count("), "php: {php}");
    }

    #[test]
    fn accessor_chunks_length_zig_uses_items_len() {
        let zig = StreamingFieldResolver::accessor("chunks.length", "zig", "chunks").unwrap();
        assert_eq!(zig, "chunks.items.len", "zig chunks.length: {zig}");
    }

    #[test]
    fn accessor_stream_content_zig_uses_content_items() {
        let zig = StreamingFieldResolver::accessor("stream_content", "zig", "chunks").unwrap();
        assert_eq!(zig, "chunks_content.items", "zig stream_content: {zig}");
    }

    #[test]
    fn collect_snippet_zig_drains_via_ffi() {
        let snip = StreamingFieldResolver::collect_snippet("zig", "_stream_handle", "chunks").unwrap();
        assert!(snip.contains("std.ArrayList([]u8)"), "zig collect: {snip}");
        assert!(snip.contains("chat_stream_next(_stream_handle)"), "zig collect: {snip}");
        assert!(snip.contains("chunks_content"), "zig collect: {snip}");
        assert!(
            snip.contains("chunks.append(std.heap.c_allocator"),
            "zig collect: {snip}"
        );
        assert!(snip.contains(".empty;"), "zig collect (Zig 0.16 unmanaged): {snip}");
    }

    #[test]
    fn accessor_stream_content_rust_uses_iterator() {
        let expr = StreamingFieldResolver::accessor("stream_content", "rust", "chunks").unwrap();
        assert!(expr.contains(".collect::<String>()"), "rust stream_content: {expr}");
    }

    #[test]
    fn accessor_no_chunks_after_done_returns_true() {
        for lang in ["rust", "go", "java", "php", "node", "wasm", "elixir"] {
            let expr = StreamingFieldResolver::accessor("no_chunks_after_done", lang, "chunks").unwrap();
            assert_eq!(expr, "true", "lang {lang}: expected 'true', got '{expr}'");
        }
    }

    #[test]
    fn accessor_elixir_chunks_length_uses_length_function() {
        let expr = StreamingFieldResolver::accessor("chunks.length", "elixir", "chunks").unwrap();
        assert_eq!(expr, "length(chunks)", "elixir chunks.length: {expr}");
    }

    #[test]
    fn accessor_elixir_stream_content_uses_pipe() {
        let expr = StreamingFieldResolver::accessor("stream_content", "elixir", "chunks").unwrap();
        assert!(expr.contains("|> Enum.join"), "elixir stream_content: {expr}");
        assert!(expr.contains("|> Enum.map"), "elixir stream_content: {expr}");
        // Elixir lists do not support bracket access — must use Enum.at, never choices[0]
        assert!(
            !expr.contains("choices[0]"),
            "elixir stream_content must not use bracket access on list: {expr}"
        );
        assert!(
            expr.contains("Enum.at("),
            "elixir stream_content must use Enum.at for list index: {expr}"
        );
    }

    #[test]
    fn accessor_elixir_stream_complete_uses_list_last() {
        let expr = StreamingFieldResolver::accessor("stream_complete", "elixir", "chunks").unwrap();
        assert!(expr.contains("List.last(chunks)"), "elixir stream_complete: {expr}");
        assert!(expr.contains("finish_reason != nil"), "elixir stream_complete: {expr}");
        // Elixir lists do not support bracket access — must use Enum.at, never choices[0]
        assert!(
            !expr.contains("choices[0]"),
            "elixir stream_complete must not use bracket access on list: {expr}"
        );
        assert!(
            expr.contains("Enum.at("),
            "elixir stream_complete must use Enum.at for list index: {expr}"
        );
    }

    #[test]
    fn accessor_elixir_finish_reason_uses_list_last() {
        let expr = StreamingFieldResolver::accessor("finish_reason", "elixir", "chunks").unwrap();
        assert!(expr.contains("List.last(chunks)"), "elixir finish_reason: {expr}");
        assert!(expr.contains("finish_reason"), "elixir finish_reason: {expr}");
        // Elixir lists do not support bracket access — must use Enum.at, never choices[0]
        assert!(
            !expr.contains("choices[0]"),
            "elixir finish_reason must not use bracket access on list: {expr}"
        );
        assert!(
            expr.contains("Enum.at("),
            "elixir finish_reason must use Enum.at for list index: {expr}"
        );
    }

    #[test]
    fn collect_snippet_elixir_uses_enum_to_list() {
        let snip = StreamingFieldResolver::collect_snippet("elixir", "result", "chunks").unwrap();
        assert!(snip.contains("Enum.to_list(result)"), "elixir: {snip}");
        assert!(snip.contains("chunks ="), "elixir: {snip}");
    }

    #[test]
    fn collect_snippet_rust_uses_tokio_stream() {
        let snip = StreamingFieldResolver::collect_snippet("rust", "result", "chunks").unwrap();
        assert!(snip.contains("tokio_stream::StreamExt::collect"), "rust: {snip}");
        assert!(snip.contains("let chunks"), "rust: {snip}");
        // Items are Result<ChatCompletionChunk, _> — unwrap so chunks is Vec<ChatCompletionChunk>
        assert!(snip.contains(".expect("), "rust must unwrap Result items: {snip}");
    }

    #[test]
    fn collect_snippet_go_drains_channel() {
        let snip = StreamingFieldResolver::collect_snippet("go", "stream", "chunks").unwrap();
        assert!(snip.contains("for chunk := range stream"), "go: {snip}");
    }

    #[test]
    fn collect_snippet_java_uses_iterator() {
        let snip = StreamingFieldResolver::collect_snippet("java", "result", "chunks").unwrap();
        // Must call .iterator() on the Stream<T> before using hasNext()/next() —
        // Stream does not implement those methods directly.
        assert!(
            snip.contains(".iterator()"),
            "java snippet must call .iterator() on stream: {snip}"
        );
        assert!(snip.contains("hasNext()"), "java: {snip}");
        assert!(snip.contains(".next()"), "java: {snip}");
    }

    #[test]
    fn collect_snippet_php_decodes_json_or_iterates() {
        let snip = StreamingFieldResolver::collect_snippet("php", "result", "chunks").unwrap();
        // PHP binding's chat_stream_async returns a JSON string today; collect-snippet
        // decodes it.  iterator_to_array is retained as the fallback branch so a
        // future binding that exposes a real iterator continues to work without
        // regenerating the e2e tests.
        assert!(snip.contains("json_decode"), "php must decode JSON: {snip}");
        assert!(
            snip.contains("iterator_to_array"),
            "php must keep iterator_to_array fallback: {snip}"
        );
        assert!(snip.contains("$chunks ="), "php must bind $chunks: {snip}");
    }

    #[test]
    fn collect_snippet_node_uses_for_await() {
        let snip = StreamingFieldResolver::collect_snippet("node", "result", "chunks").unwrap();
        assert!(snip.contains("for await"), "node: {snip}");
    }

    #[test]
    fn collect_snippet_python_uses_async_for() {
        let snip = StreamingFieldResolver::collect_snippet("python", "result", "chunks").unwrap();
        assert!(snip.contains("async for chunk in result"), "python: {snip}");
        assert!(snip.contains("chunks.append(chunk)"), "python: {snip}");
    }

    #[test]
    fn accessor_stream_content_python_uses_join() {
        let expr = StreamingFieldResolver::accessor("stream_content", "python", "chunks").unwrap();
        assert!(expr.contains("\"\".join("), "python stream_content: {expr}");
        assert!(expr.contains("c.choices"), "python stream_content: {expr}");
    }

    #[test]
    fn accessor_stream_complete_python_uses_finish_reason() {
        let expr = StreamingFieldResolver::accessor("stream_complete", "python", "chunks").unwrap();
        assert!(
            expr.contains("finish_reason is not None"),
            "python stream_complete: {expr}"
        );
    }

    #[test]
    fn accessor_finish_reason_python_uses_last_chunk() {
        let expr = StreamingFieldResolver::accessor("finish_reason", "python", "chunks").unwrap();
        assert!(expr.contains("chunks[-1]"), "python finish_reason: {expr}");
        // Must wrap in str() so FinishReason enum objects support .strip() comparisons
        assert!(
            expr.starts_with("(str(") || expr.contains("str(chunks"),
            "python finish_reason must wrap in str(): {expr}"
        );
    }

    #[test]
    fn accessor_tool_calls_python_uses_list_comprehension() {
        let expr = StreamingFieldResolver::accessor("tool_calls", "python", "chunks").unwrap();
        assert!(expr.contains("for c in chunks"), "python tool_calls: {expr}");
        assert!(expr.contains("tool_calls"), "python tool_calls: {expr}");
    }

    #[test]
    fn accessor_usage_python_uses_last_chunk() {
        let expr = StreamingFieldResolver::accessor("usage", "python", "chunks").unwrap();
        assert!(
            expr.contains("chunks[-1].usage"),
            "python usage: expected chunks[-1].usage, got: {expr}"
        );
    }

    #[test]
    fn accessor_usage_total_tokens_does_not_route_via_chunks() {
        // `usage` is intentionally NOT a streaming-virtual root (it overlaps the
        // non-streaming response shape). The accessor must return None so the
        // assertion falls through to the normal field-path codegen.
        assert!(StreamingFieldResolver::accessor("usage.total_tokens", "python", "chunks").is_none());
    }

    #[test]
    fn accessor_unknown_field_returns_none() {
        assert_eq!(
            StreamingFieldResolver::accessor("nonexistent_field", "rust", "chunks"),
            None
        );
    }

    // -----------------------------------------------------------------------
    // Deep-path tests: tool_calls[0].function.name and tool_calls[0].id
    // -----------------------------------------------------------------------

    #[test]
    fn is_streaming_virtual_field_recognizes_deep_tool_calls_paths() {
        assert!(
            is_streaming_virtual_field("tool_calls[0].function.name"),
            "tool_calls[0].function.name should be recognized"
        );
        assert!(
            is_streaming_virtual_field("tool_calls[0].id"),
            "tool_calls[0].id should be recognized"
        );
        assert!(
            is_streaming_virtual_field("tool_calls[1].function.arguments"),
            "tool_calls[1].function.arguments should be recognized"
        );
        // bare root still recognized
        assert!(is_streaming_virtual_field("tool_calls"));
        // unrelated deep path must NOT be recognized
        assert!(!is_streaming_virtual_field("tool_calls_extra.name"));
        assert!(!is_streaming_virtual_field("nonexistent[0].field"));
    }

    /// Snapshot: `tool_calls[0].function.name` for Rust, Kotlin, TypeScript.
    ///
    /// These three languages cover the main accessor styles:
    /// - Rust: snake_case field, explicit `[0]` index on collected Vec
    /// - Kotlin: camelCase method calls with `.first()` for index 0
    /// - TypeScript/Node: camelCase properties with `[0]` bracket
    #[test]
    fn deep_tool_calls_function_name_snapshot_rust_kotlin_ts() {
        let field = "tool_calls[0].function.name";

        let rust = StreamingFieldResolver::accessor(field, "rust", "chunks").unwrap();
        // Rust: Option-aware chain over the iterator — `.nth(0)` then `.and_then`
        // on each Option-wrapped field (function is Option<StreamFunctionCall>,
        // name is Option<String>). Final `.unwrap_or("")` yields `&str`.
        assert!(
            rust.contains(".nth(0)"),
            "rust deep tool_calls: expected .nth(0) iterator index, got: {rust}"
        );
        assert!(
            rust.contains("x.function.as_ref()"),
            "rust deep tool_calls: expected Option-aware function access, got: {rust}"
        );
        assert!(
            rust.contains("x.name.as_deref()"),
            "rust deep tool_calls: expected Option-aware name leaf, got: {rust}"
        );
        assert!(
            !rust.contains("// skipped"),
            "rust deep tool_calls: must not emit skip comment, got: {rust}"
        );

        let kotlin = StreamingFieldResolver::accessor(field, "kotlin", "chunks").unwrap();
        // Kotlin: uses .first() for index 0, then .function().name()
        assert!(
            kotlin.contains(".first()"),
            "kotlin deep tool_calls: expected .first() for index 0, got: {kotlin}"
        );
        assert!(
            kotlin.contains(".function()"),
            "kotlin deep tool_calls: expected .function() method call, got: {kotlin}"
        );
        assert!(
            kotlin.contains(".name()"),
            "kotlin deep tool_calls: expected .name() method call, got: {kotlin}"
        );

        let ts = StreamingFieldResolver::accessor(field, "node", "chunks").unwrap();
        // TypeScript/Node: uses [0] then .function.name (camelCase)
        assert!(
            ts.contains("[0]"),
            "ts/node deep tool_calls: expected [0] index, got: {ts}"
        );
        assert!(
            ts.contains(".function"),
            "ts/node deep tool_calls: expected .function segment, got: {ts}"
        );
        assert!(
            ts.contains(".name"),
            "ts/node deep tool_calls: expected .name segment, got: {ts}"
        );
    }

    #[test]
    fn deep_tool_calls_id_snapshot_all_langs() {
        let field = "tool_calls[0].id";

        let rust = StreamingFieldResolver::accessor(field, "rust", "chunks").unwrap();
        assert!(rust.contains(".nth(0)"), "rust: {rust}");
        assert!(rust.contains("x.id.as_deref()"), "rust: {rust}");

        let go = StreamingFieldResolver::accessor(field, "go", "chunks").unwrap();
        assert!(go.contains("[0]"), "go: {go}");
        // Go: ID is a well-known initialism → uppercase
        assert!(go.contains(".ID"), "go: expected .ID initialism, got: {go}");

        let python = StreamingFieldResolver::accessor(field, "python", "chunks").unwrap();
        assert!(python.contains("[0]"), "python: {python}");
        assert!(python.contains(".id"), "python: {python}");

        let php = StreamingFieldResolver::accessor(field, "php", "chunks").unwrap();
        assert!(php.contains("[0]"), "php: {php}");
        assert!(php.contains("->id"), "php: expected ->id, got: {php}");

        let java = StreamingFieldResolver::accessor(field, "java", "chunks").unwrap();
        assert!(java.contains(".get(0)"), "java: expected .get(0), got: {java}");
        assert!(java.contains(".id()"), "java: expected .id() method call, got: {java}");

        let csharp = StreamingFieldResolver::accessor(field, "csharp", "chunks").unwrap();
        assert!(csharp.contains("[0]"), "csharp: {csharp}");
        assert!(
            csharp.contains(".Id"),
            "csharp: expected .Id (PascalCase), got: {csharp}"
        );

        let elixir = StreamingFieldResolver::accessor(field, "elixir", "chunks").unwrap();
        assert!(elixir.contains("Enum.at("), "elixir: expected Enum.at(, got: {elixir}");
        assert!(elixir.contains(".id"), "elixir: {elixir}");
    }

    #[test]
    fn deep_tool_calls_function_name_snapshot_python_elixir_zig() {
        let field = "tool_calls[0].function.name";

        let python = StreamingFieldResolver::accessor(field, "python", "chunks").unwrap();
        assert!(python.contains("[0]"), "python: {python}");
        assert!(python.contains(".function"), "python: {python}");
        assert!(python.contains(".name"), "python: {python}");

        let elixir = StreamingFieldResolver::accessor(field, "elixir", "chunks").unwrap();
        // Elixir: Enum.at(…, 0).function.name
        assert!(elixir.contains("Enum.at("), "elixir: {elixir}");
        assert!(elixir.contains(".function"), "elixir: {elixir}");
        assert!(elixir.contains(".name"), "elixir: {elixir}");

        // Zig stores chunks as JSON strings, not typed records — deep
        // tool_calls paths are unsupported and resolve to None so the
        // assertion site can skip them.
        assert!(
            StreamingFieldResolver::accessor(field, "zig", "chunks").is_none(),
            "zig: expected None for deep tool_calls path"
        );
    }

    #[test]
    fn parse_tail_parses_index_then_field_segments() {
        let segs = parse_tail("[0].function.name");
        assert_eq!(segs.len(), 3, "expected 3 segments, got: {segs:?}");
        assert_eq!(segs[0], TailSeg::Index(0));
        assert_eq!(segs[1], TailSeg::Field("function".to_string()));
        assert_eq!(segs[2], TailSeg::Field("name".to_string()));
    }

    #[test]
    fn parse_tail_parses_simple_index_field() {
        let segs = parse_tail("[0].id");
        assert_eq!(segs.len(), 2, "expected 2 segments, got: {segs:?}");
        assert_eq!(segs[0], TailSeg::Index(0));
        assert_eq!(segs[1], TailSeg::Field("id".to_string()));
    }

    #[test]
    fn parse_tail_handles_nonzero_index() {
        let segs = parse_tail("[2].function.arguments");
        assert_eq!(segs[0], TailSeg::Index(2));
        assert_eq!(segs[1], TailSeg::Field("function".to_string()));
        assert_eq!(segs[2], TailSeg::Field("arguments".to_string()));
    }

    // -----------------------------------------------------------------------
    // Swift-specific accessor tests
    // -----------------------------------------------------------------------

    #[test]
    fn accessor_chunks_length_swift_uses_count() {
        let swift = StreamingFieldResolver::accessor("chunks.length", "swift", "chunks").unwrap();
        assert_eq!(swift, "chunks.count", "swift chunks.length: {swift}");
    }

    #[test]
    fn accessor_stream_content_swift_uses_swift_closures() {
        let expr = StreamingFieldResolver::accessor("stream_content", "swift", "chunks").unwrap();
        // Must use Swift closure syntax (`{ ... }`) not JS arrow (`=>`)
        assert!(
            expr.contains("{ c in"),
            "swift stream_content must use Swift closure syntax, got: {expr}"
        );
        assert!(
            !expr.contains("=>"),
            "swift stream_content must not contain JS arrow `=>`, got: {expr}"
        );
        // Content is accessed via method call chains
        assert!(
            expr.contains("choices()"),
            "swift stream_content must use .choices() method call, got: {expr}"
        );
        assert!(
            expr.contains("delta()"),
            "swift stream_content must use .delta() method call, got: {expr}"
        );
        assert!(
            expr.contains("content()"),
            "swift stream_content must use .content() method call, got: {expr}"
        );
        assert!(
            expr.contains(".toString()"),
            "swift stream_content must convert RustString via .toString(), got: {expr}"
        );
        assert!(
            expr.contains(".joined()"),
            "swift stream_content must join with .joined(), got: {expr}"
        );
        // Must not use JS .length or .join('')
        assert!(
            !expr.contains(".length"),
            "swift stream_content must not use JS .length, got: {expr}"
        );
        assert!(
            !expr.contains(".join("),
            "swift stream_content must not use JS .join(, got: {expr}"
        );
    }

    #[test]
    fn accessor_stream_complete_swift_uses_swift_syntax() {
        let expr = StreamingFieldResolver::accessor("stream_complete", "swift", "chunks").unwrap();
        // Must use Swift isEmpty / last! syntax, not JS .length
        assert!(
            expr.contains("isEmpty"),
            "swift stream_complete must use .isEmpty, got: {expr}"
        );
        assert!(
            expr.contains(".last!"),
            "swift stream_complete must use .last!, got: {expr}"
        );
        assert!(
            expr.contains("choices()"),
            "swift stream_complete must use .choices() method call, got: {expr}"
        );
        assert!(
            expr.contains("finish_reason()"),
            "swift stream_complete must use .finish_reason(), got: {expr}"
        );
        assert!(
            !expr.contains(".length"),
            "swift stream_complete must not use JS .length, got: {expr}"
        );
        assert!(
            !expr.contains("!= null"),
            "swift stream_complete must not use JS `!= null`, got: {expr}"
        );
    }

    #[test]
    fn accessor_tool_calls_swift_uses_swift_flatmap() {
        let expr = StreamingFieldResolver::accessor("tool_calls", "swift", "chunks").unwrap();
        // Must use Swift closure syntax, not JS arrow
        assert!(
            !expr.contains("=>"),
            "swift tool_calls must not contain JS arrow `=>`, got: {expr}"
        );
        assert!(
            expr.contains("flatMap"),
            "swift tool_calls must use flatMap, got: {expr}"
        );
        assert!(
            expr.contains("choices()"),
            "swift tool_calls must use .choices() method call, got: {expr}"
        );
        assert!(
            expr.contains("delta()"),
            "swift tool_calls must use .delta() method call, got: {expr}"
        );
        assert!(
            expr.contains("tool_calls()"),
            "swift tool_calls must use .tool_calls() method call, got: {expr}"
        );
    }

    #[test]
    fn accessor_tool_calls_deep_path_swift_uses_method_calls_with_optional_chain() {
        // `tool_calls[0].function.name` must resolve to Swift method calls with
        // optional chaining because swift-bridge opaque refs expose fields as
        // methods that return Optional.
        let expr = StreamingFieldResolver::accessor("tool_calls[0].function.name", "swift", "chunks").unwrap();
        assert!(
            expr.contains("function()"),
            "swift deep tool_calls must use .function() method call, got: {expr}"
        );
        assert!(
            expr.contains("name()"),
            "swift deep tool_calls must use .name() method call, got: {expr}"
        );
        assert!(
            expr.contains(".toString()"),
            "swift deep tool_calls must convert RustString via .toString(), got: {expr}"
        );
        assert!(
            !expr.contains("=>"),
            "swift deep tool_calls must not use JS arrow syntax, got: {expr}"
        );
    }

    #[test]
    fn accessor_finish_reason_swift_uses_swift_syntax() {
        let expr = StreamingFieldResolver::accessor("finish_reason", "swift", "chunks").unwrap();
        // Must use Swift isEmpty / last! syntax, not JS .length / undefined
        assert!(
            expr.contains("isEmpty"),
            "swift finish_reason must use .isEmpty, got: {expr}"
        );
        assert!(
            expr.contains(".last!"),
            "swift finish_reason must use .last!, got: {expr}"
        );
        assert!(
            expr.contains("finish_reason()"),
            "swift finish_reason must use .finish_reason() method call, got: {expr}"
        );
        assert!(
            expr.contains(".toString()"),
            "swift finish_reason must convert RustString via .toString(), got: {expr}"
        );
        assert!(
            !expr.contains("undefined"),
            "swift finish_reason must not use JS `undefined`, got: {expr}"
        );
        assert!(
            !expr.contains(".length"),
            "swift finish_reason must not use JS .length, got: {expr}"
        );
    }

    #[test]
    fn accessor_usage_swift_uses_swift_syntax() {
        let expr = StreamingFieldResolver::accessor("usage", "swift", "chunks").unwrap();
        // Must use Swift isEmpty / last! syntax, not JS .length / undefined
        assert!(expr.contains("isEmpty"), "swift usage must use .isEmpty, got: {expr}");
        assert!(expr.contains(".last!"), "swift usage must use .last!, got: {expr}");
        assert!(
            expr.contains("usage()"),
            "swift usage must use .usage() method call, got: {expr}"
        );
        assert!(
            !expr.contains("undefined"),
            "swift usage must not use JS `undefined`, got: {expr}"
        );
        assert!(
            !expr.contains(".length"),
            "swift usage must not use JS .length, got: {expr}"
        );
    }

    // ---------------------------------------------------------------------------
    // Bug regression: kotlin_android streaming assertions use property access
    // ---------------------------------------------------------------------------

    #[test]
    fn kotlin_android_collect_snippet_uses_flow_to_list() {
        let snip = StreamingFieldResolver::collect_snippet("kotlin_android", "result", "chunks").unwrap();
        // Flow.toList() — not Iterator.asSequence().toList()
        assert!(
            snip.contains("result.toList()"),
            "kotlin_android collect must use Flow.toList(), got: {snip}"
        );
        assert!(
            !snip.contains("asSequence()"),
            "kotlin_android collect must NOT use asSequence(), got: {snip}"
        );
    }

    #[test]
    fn kotlin_android_stream_content_uses_property_access() {
        let expr = StreamingFieldResolver::accessor("stream_content", "kotlin_android", "chunks").unwrap();
        assert!(
            expr.contains(".choices"),
            "kotlin_android stream_content must use .choices property, got: {expr}"
        );
        assert!(
            !expr.contains(".choices()"),
            "kotlin_android stream_content must NOT use .choices() getter, got: {expr}"
        );
        assert!(
            expr.contains(".delta"),
            "kotlin_android stream_content must use .delta property, got: {expr}"
        );
        assert!(
            !expr.contains(".delta()"),
            "kotlin_android stream_content must NOT use .delta() getter, got: {expr}"
        );
        assert!(
            expr.contains(".content"),
            "kotlin_android stream_content must use .content property, got: {expr}"
        );
        assert!(
            !expr.contains(".content()"),
            "kotlin_android stream_content must NOT use .content() getter, got: {expr}"
        );
    }

    #[test]
    fn kotlin_android_finish_reason_uses_name_lowercase_not_get_value() {
        let expr = StreamingFieldResolver::accessor("finish_reason", "kotlin_android", "chunks").unwrap();
        assert!(
            expr.contains(".finishReason"),
            "kotlin_android finish_reason must use .finishReason property, got: {expr}"
        );
        assert!(
            !expr.contains(".finishReason()"),
            "kotlin_android finish_reason must NOT use .finishReason() getter, got: {expr}"
        );
        assert!(
            expr.contains(".name"),
            "kotlin_android finish_reason must use .name for enum wire value, got: {expr}"
        );
        assert!(
            expr.contains(".lowercase()"),
            "kotlin_android finish_reason must use .lowercase(), got: {expr}"
        );
        assert!(
            !expr.contains(".getValue()"),
            "kotlin_android finish_reason must NOT use .getValue(), got: {expr}"
        );
    }

    #[test]
    fn kotlin_android_usage_uses_property_access() {
        let expr = StreamingFieldResolver::accessor("usage", "kotlin_android", "chunks").unwrap();
        assert!(
            expr.contains(".usage"),
            "kotlin_android usage must use .usage property, got: {expr}"
        );
        assert!(
            !expr.contains(".usage()"),
            "kotlin_android usage must NOT use .usage() getter, got: {expr}"
        );
    }

    #[test]
    fn kotlin_android_deep_tool_calls_uses_property_access() {
        let expr = StreamingFieldResolver::accessor("tool_calls[0].function.name", "kotlin_android", "chunks").unwrap();
        assert!(
            expr.contains(".function"),
            "kotlin_android deep tool_calls must use .function property, got: {expr}"
        );
        assert!(
            !expr.contains(".function()"),
            "kotlin_android deep tool_calls must NOT use .function() getter, got: {expr}"
        );
        assert!(
            expr.contains(".name"),
            "kotlin_android deep tool_calls must use .name property, got: {expr}"
        );
        assert!(
            !expr.contains(".name()"),
            "kotlin_android deep tool_calls must NOT use .name() getter, got: {expr}"
        );
    }
}