alef-core 0.17.1

Core types, config schema, and backend trait for the alef polyglot binding generator
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
//! E2E test generation configuration types.

use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};

/// Controls whether generated e2e test projects reference the package under
/// test via a local path (for development) or a registry version string
/// (for standalone `test_apps` that consumers can run without the monorepo).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum DependencyMode {
    /// Local path dependency (default) — used during normal e2e development.
    #[default]
    Local,
    /// Registry dependency — generates standalone test apps that pull the
    /// package from its published registry (PyPI, npm, crates.io, etc.).
    Registry,
}

/// Configuration for registry-mode e2e generation (`alef e2e generate --registry`).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RegistryConfig {
    /// Output directory for registry-mode test apps (default: "test_apps").
    #[serde(default = "default_test_apps_dir")]
    pub output: String,
    /// Per-language package overrides used only in registry mode.
    /// Merged on top of the base `[e2e.packages]` entries.
    #[serde(default)]
    pub packages: HashMap<String, PackageRef>,
    /// When non-empty, only fixture categories in this list are included in
    /// registry-mode generation (useful for shipping a curated subset).
    #[serde(default)]
    pub categories: Vec<String>,
    /// GitHub repository URL for downloading prebuilt artifacts (e.g., FFI
    /// shared libraries) from GitHub Releases.
    ///
    /// Falls back to `[scaffold] repository` when not set, then to
    /// `https://github.com/kreuzberg-dev/{crate.name}`.
    #[serde(default)]
    pub github_repo: Option<String>,
}

impl Default for RegistryConfig {
    fn default() -> Self {
        Self {
            output: default_test_apps_dir(),
            packages: HashMap::new(),
            categories: Vec::new(),
            github_repo: None,
        }
    }
}

fn default_test_apps_dir() -> String {
    "test_apps".to_string()
}

/// Root e2e configuration from `[e2e]` section of alef.toml.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct E2eConfig {
    /// Directory containing fixture JSON files (default: "fixtures").
    #[serde(default = "default_fixtures_dir")]
    pub fixtures: String,
    /// Output directory for generated e2e test projects (default: "e2e").
    #[serde(default = "default_output_dir")]
    pub output: String,
    /// Repo-root-relative directory holding binary file fixtures referenced by
    /// `file_path` / `bytes` fixture args (default: "test_documents").
    ///
    /// Backends that emit chdir / setup hooks for file-based fixtures resolve
    /// the relative path from the test-emission directory via
    /// [`E2eConfig::test_documents_relative_from`]. The default matches the
    /// kreuzberg convention; downstream crates whose fixtures don't reference
    /// files (e.g. liter-llm, which uses pure mock-server fixtures) can leave
    /// the default in place — backends conditionally emit the setup only when
    /// fixtures actually need it.
    #[serde(default = "default_test_documents_dir")]
    pub test_documents_dir: String,
    /// Languages to generate e2e tests for. Defaults to top-level `languages` list.
    #[serde(default)]
    pub languages: Vec<String>,
    /// Default function call configuration.
    pub call: CallConfig,
    /// Named additional call configurations for multi-function testing.
    /// Fixtures reference these via the `call` field, e.g. `"call": "embed"`.
    #[serde(default)]
    pub calls: HashMap<String, CallConfig>,
    /// Per-language package reference overrides.
    #[serde(default)]
    pub packages: HashMap<String, PackageRef>,
    /// Per-language formatter commands.
    #[serde(default)]
    pub format: HashMap<String, String>,
    /// Field path aliases: maps fixture field paths to actual API struct paths.
    /// E.g., "metadata.title" -> "metadata.document.title"
    /// Supports struct access (foo.bar), map access (foo[key]), direct fields.
    #[serde(default)]
    pub fields: HashMap<String, String>,
    /// Fields that are Optional/nullable in the return type.
    /// Rust generators use .as_deref().unwrap_or("") for strings, .is_some() for structs.
    #[serde(default)]
    pub fields_optional: HashSet<String>,
    /// Fields that are arrays/Vecs on the result type.
    /// When a fixture path like `json_ld.name` traverses an array field, the
    /// accessor adds `[0]` (or language equivalent) to index into the first element.
    #[serde(default)]
    pub fields_array: HashSet<String>,
    /// Fields where the accessor is a method call (appends `()`) rather than a field access.
    /// Rust-specific: Java always uses `()`, Python/PHP use field access.
    /// Listed as the full resolved field path (after alias resolution).
    /// E.g., `"metadata.format.excel"` means `.excel` should be emitted as `.excel()`.
    #[serde(default)]
    pub fields_method_calls: HashSet<String>,
    /// Known top-level fields on the result type.
    ///
    /// When non-empty, assertions whose resolved field path starts with a
    /// segment that is NOT in this set are emitted as comments (skipped)
    /// instead of executable assertions.  This prevents broken assertions
    /// when fixtures reference fields from a different operation (e.g.,
    /// `batch.completed_count` on a `ScrapeResult`).
    #[serde(default)]
    pub result_fields: HashSet<String>,
    /// Fixture categories excluded from cross-language e2e codegen.
    ///
    /// Fixtures whose resolved category matches an entry in this set are
    /// skipped by every per-language e2e generator — no test is emitted at
    /// all (no skip directive, no commented-out body). The fixture files stay
    /// on disk and remain available to Rust integration tests inside the
    /// consumer crate's own `tests/` directory.
    ///
    /// Use this to keep fixtures that exercise internal middleware (cache,
    /// proxy, budget, hooks, etc.) out of bindings whose public surface does
    /// not expose those layers.
    ///
    /// Example:
    /// ```toml
    /// [e2e]
    /// exclude_categories = ["cache", "proxy", "budget", "hooks"]
    /// ```
    #[serde(default)]
    pub exclude_categories: HashSet<String>,
    /// C FFI accessor type chain: maps `"{parent_snake_type}.{field}"` to the
    /// PascalCase return type name (without prefix).
    ///
    /// Used by the C e2e generator to emit chained FFI accessor calls for
    /// nested field paths. The root type is always `conversion_result`.
    ///
    /// Example:
    /// ```toml
    /// [e2e.fields_c_types]
    /// "conversion_result.metadata" = "HtmlMetadata"
    /// "html_metadata.document" = "DocumentMetadata"
    /// ```
    #[serde(default)]
    pub fields_c_types: HashMap<String, String>,
    /// Fields whose resolved type is an enum in the generated bindings.
    ///
    /// When a `contains` / `contains_all` / etc. assertion targets one of these
    /// fields, language generators that cannot call `.contains()` directly on an
    /// enum (e.g., Java) will emit a string-conversion call first.  For Java,
    /// the generated assertion calls `.getValue()` on the enum — the `@JsonValue`
    /// method that all alef-generated Java enums expose — to obtain the lowercase
    /// serde string before performing the string comparison.
    ///
    /// Both the raw fixture field path (before alias resolution) and the resolved
    /// path (after alias resolution via `[e2e.fields]`) are accepted, so you can
    /// use either form:
    ///
    /// ```toml
    /// # Raw fixture field:
    /// fields_enum = ["links[].link_type", "assets[].category"]
    /// # …or the resolved (aliased) field name:
    /// fields_enum = ["links[].link_type", "assets[].asset_category"]
    /// ```
    #[serde(default)]
    pub fields_enum: HashSet<String>,
    /// Dependency mode: `Local` (default) or `Registry`.
    /// Set at runtime via `--registry` CLI flag; not serialized from TOML.
    #[serde(skip)]
    pub dep_mode: DependencyMode,
    /// Registry-mode configuration from `[e2e.registry]`.
    #[serde(default)]
    pub registry: RegistryConfig,
}

impl E2eConfig {
    /// Resolve the call config for a fixture. Uses the named call if specified,
    /// otherwise falls back to the default `[e2e.call]`.
    pub fn resolve_call(&self, call_name: Option<&str>) -> &CallConfig {
        match call_name {
            Some(name) => self.calls.get(name).unwrap_or(&self.call),
            None => &self.call,
        }
    }

    /// Resolve the call config for a fixture, applying `select_when` auto-routing.
    ///
    /// When the fixture has an explicit `call` name, that named config is returned
    /// (same as [`resolve_call`]).  When the fixture has no explicit call, the method
    /// scans named calls for a [`SelectWhen`] condition that matches the fixture's
    /// shape (id, category, tags, input) and returns the first match.  If no condition
    /// matches, it falls back to the default `[e2e.call]`.
    ///
    /// All non-`None` discriminators on a `SelectWhen` must match (logical AND) for
    /// the condition to fire. A `SelectWhen` with every field `None` never matches —
    /// at least one discriminator must be set.
    pub fn resolve_call_for_fixture(
        &self,
        call_name: Option<&str>,
        fixture_id: &str,
        fixture_category: &str,
        fixture_tags: &[String],
        fixture_input: &serde_json::Value,
    ) -> &CallConfig {
        if let Some(name) = call_name {
            return self.calls.get(name).unwrap_or(&self.call);
        }
        // Auto-route by select_when condition. Deterministic order: sort by call name.
        let mut names: Vec<&String> = self.calls.keys().collect();
        names.sort();
        for name in names {
            let call_config = &self.calls[name];
            if let Some(sel) = &call_config.select_when {
                if sel.matches(fixture_id, fixture_category, fixture_tags, fixture_input) {
                    return call_config;
                }
            }
        }
        &self.call
    }

    /// Resolve the effective package reference for a language.
    ///
    /// In registry mode, entries from `[e2e.registry.packages]` are merged on
    /// top of the base `[e2e.packages]` — registry overrides win for any field
    /// that is `Some`.
    pub fn resolve_package(&self, lang: &str) -> Option<PackageRef> {
        let base = self.packages.get(lang);
        if self.dep_mode == DependencyMode::Registry {
            let reg = self.registry.packages.get(lang);
            match (base, reg) {
                (Some(b), Some(r)) => Some(PackageRef {
                    name: r.name.clone().or_else(|| b.name.clone()),
                    path: r.path.clone().or_else(|| b.path.clone()),
                    module: r.module.clone().or_else(|| b.module.clone()),
                    version: r.version.clone().or_else(|| b.version.clone()),
                }),
                (None, Some(r)) => Some(r.clone()),
                (Some(b), None) => Some(b.clone()),
                (None, None) => None,
            }
        } else {
            base.cloned()
        }
    }

    /// Return the effective `result_fields` for `call`.
    ///
    /// Returns `call.result_fields` when non-empty, otherwise the global
    /// `self.result_fields`.
    pub fn effective_result_fields<'a>(&'a self, call: &'a CallConfig) -> &'a HashSet<String> {
        if !call.result_fields.is_empty() {
            &call.result_fields
        } else {
            &self.result_fields
        }
    }

    /// Return the effective `fields` alias map for `call`.
    pub fn effective_fields<'a>(&'a self, call: &'a CallConfig) -> &'a HashMap<String, String> {
        if !call.fields.is_empty() {
            &call.fields
        } else {
            &self.fields
        }
    }

    /// Return the effective `fields_optional` for `call`.
    pub fn effective_fields_optional<'a>(&'a self, call: &'a CallConfig) -> &'a HashSet<String> {
        if !call.fields_optional.is_empty() {
            &call.fields_optional
        } else {
            &self.fields_optional
        }
    }

    /// Return the effective `fields_array` for `call`.
    pub fn effective_fields_array<'a>(&'a self, call: &'a CallConfig) -> &'a HashSet<String> {
        if !call.fields_array.is_empty() {
            &call.fields_array
        } else {
            &self.fields_array
        }
    }

    /// Return the effective `fields_method_calls` for `call`.
    pub fn effective_fields_method_calls<'a>(&'a self, call: &'a CallConfig) -> &'a HashSet<String> {
        if !call.fields_method_calls.is_empty() {
            &call.fields_method_calls
        } else {
            &self.fields_method_calls
        }
    }

    /// Return the effective `fields_enum` for `call`.
    pub fn effective_fields_enum<'a>(&'a self, call: &'a CallConfig) -> &'a HashSet<String> {
        if !call.fields_enum.is_empty() {
            &call.fields_enum
        } else {
            &self.fields_enum
        }
    }

    /// Return the effective `fields_c_types` for `call`.
    pub fn effective_fields_c_types<'a>(&'a self, call: &'a CallConfig) -> &'a HashMap<String, String> {
        if !call.fields_c_types.is_empty() {
            &call.fields_c_types
        } else {
            &self.fields_c_types
        }
    }

    /// Return the effective output directory: `registry.output` in registry
    /// mode, `output` otherwise.
    pub fn effective_output(&self) -> &str {
        if self.dep_mode == DependencyMode::Registry {
            &self.registry.output
        } else {
            &self.output
        }
    }

    /// Relative path from a backend's emission directory to the
    /// `test_documents_dir` at the repo root.
    ///
    /// `emission_depth` counts the number of additional `../` segments needed
    /// to reach `<output>/<lang>/` from where the file is being emitted:
    ///
    /// * `0` — emitted directly at `e2e/<lang>/` (e.g. dart, zig `build.zig`)
    /// * `1` — emitted at `e2e/<lang>/<sub>/` (e.g. ruby `spec/`, R `tests/`)
    /// * `2` — emitted at `e2e/<lang>/<sub1>/<sub2>/`
    ///
    /// The base prefix is two segments above `<output>/<lang>/` (i.e.
    /// `../../`), matching the canonical layout where `<output>` (default
    /// `"e2e"`) sits at the repo root next to the configured
    /// `test_documents_dir`.
    pub fn test_documents_relative_from(&self, emission_depth: usize) -> String {
        let mut up = String::from("../../");
        for _ in 0..emission_depth {
            up.push_str("../");
        }
        format!("{up}{}", self.test_documents_dir)
    }
}

fn default_fixtures_dir() -> String {
    "fixtures".to_string()
}

fn default_output_dir() -> String {
    "e2e".to_string()
}

fn default_test_documents_dir() -> String {
    "test_documents".to_string()
}

/// Hand-rolled `Default` so the `test_documents_dir` field receives its
/// `default_test_documents_dir()` value (`"test_documents"`) when callers use
/// `..Default::default()` to construct an `E2eConfig` literally rather than
/// going through `serde::Deserialize`. Without this, `derive(Default)` would
/// fall back to `String::default()` (i.e. the empty string), and any backend
/// computing `test_documents_relative_from(0)` would emit `"../../"` (no dir
/// component), breaking generated chdir hooks.
impl Default for E2eConfig {
    fn default() -> Self {
        Self {
            fixtures: default_fixtures_dir(),
            output: default_output_dir(),
            test_documents_dir: default_test_documents_dir(),
            languages: Vec::new(),
            call: CallConfig::default(),
            calls: HashMap::new(),
            packages: HashMap::new(),
            format: HashMap::new(),
            fields: HashMap::new(),
            fields_optional: HashSet::new(),
            fields_array: HashSet::new(),
            fields_method_calls: HashSet::new(),
            result_fields: HashSet::new(),
            exclude_categories: HashSet::new(),
            fields_c_types: HashMap::new(),
            fields_enum: HashSet::new(),
            dep_mode: DependencyMode::default(),
            registry: RegistryConfig::default(),
        }
    }
}

/// Configuration for the function call in each test.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct CallConfig {
    /// Per-call override for `result_fields`.
    ///
    /// When non-empty, this set replaces the global `[e2e].result_fields` for
    /// fixtures routed to this call.  Use this when different API functions return
    /// differently-shaped structs so each call can gate its own field set.
    ///
    /// Example:
    /// ```toml
    /// [e2e.calls.crawl]
    /// result_fields = ["pages", "final_url", "stayed_on_domain"]
    /// ```
    #[serde(default)]
    pub result_fields: HashSet<String>,
    /// Per-call override for `[e2e].fields` alias map.
    ///
    /// When non-empty, replaces (not merges with) the global `fields` map for
    /// fixtures routed to this call.
    #[serde(default)]
    pub fields: HashMap<String, String>,
    /// Per-call override for `[e2e].fields_optional`.
    #[serde(default)]
    pub fields_optional: HashSet<String>,
    /// Per-call override for `[e2e].fields_array`.
    #[serde(default)]
    pub fields_array: HashSet<String>,
    /// Per-call override for `[e2e].fields_method_calls`.
    #[serde(default)]
    pub fields_method_calls: HashSet<String>,
    /// Per-call override for `[e2e].fields_enum`.
    #[serde(default)]
    pub fields_enum: HashSet<String>,
    /// Per-call override for `[e2e].fields_c_types`.
    #[serde(default)]
    pub fields_c_types: HashMap<String, String>,
    /// The function name (alef applies language naming conventions).
    #[serde(default)]
    pub function: String,
    /// The module/package where the function lives.
    #[serde(default)]
    pub module: String,
    /// Variable name for the return value (default: "result").
    #[serde(default = "default_result_var")]
    pub result_var: String,
    /// Whether the function is async.
    #[serde(default)]
    pub r#async: bool,
    /// HTTP endpoint path for mock server routing (e.g., `"/v1/chat/completions"`).
    ///
    /// Required when fixtures use `mock_response`. The Rust e2e generator uses
    /// this to build the `MockRoute` that the mock server matches against.
    #[serde(default)]
    pub path: Option<String>,
    /// HTTP method for mock server routing (default: `"POST"`).
    ///
    /// Used together with `path` when building `MockRoute` entries.
    #[serde(default)]
    pub method: Option<String>,
    /// How fixture `input` fields map to function arguments.
    #[serde(default)]
    pub args: Vec<ArgMapping>,
    /// Per-language overrides for module/function/etc.
    #[serde(default)]
    pub overrides: HashMap<String, CallOverride>,
    /// Whether the function returns `Result<T, E>` in its native binding.
    /// Defaults to `true`. When `false`, generators that distinguish Result-returning
    /// from non-Result-returning calls (currently Rust) will skip the
    /// `.expect("should succeed")` unwrap and bind the raw return value directly.
    #[serde(default = "default_returns_result")]
    pub returns_result: bool,
    /// Whether the function returns only an error/unit — i.e., `Result<(), E>`.
    ///
    /// When combined with `returns_result = true`, Go generators emit `err := func()`
    /// (single return value) rather than `_, err := func()` (two return values).
    /// This is needed for functions like `validate_host` that return only `error` in Go.
    #[serde(default)]
    pub returns_void: bool,
    /// skip_languages
    #[serde(default)]
    pub skip_languages: Vec<String>,
    /// When `true`, the function returns a primitive (e.g. `String`, `bool`,
    /// `i32`) rather than a struct.  Generators that would otherwise emit
    /// `result.<field>` will fall back to the bare result variable.
    ///
    /// This is a property of the Rust core's return type and therefore identical
    /// across every binding — set it on the call, not in per-language overrides.
    /// The same flag is also accepted under `[e2e.calls.<name>.overrides.<lang>]`
    /// for backwards compatibility, but the call-level value takes precedence.
    #[serde(default)]
    pub result_is_simple: bool,
    /// When `true`, the function returns `Vec<T>` / `Array<T>`.  Generators that
    /// support per-element field assertions (rust, csharp) iterate or index into
    /// the result; the typescript codegen indexes `[0]` to mirror csharp.
    ///
    /// As with `result_is_simple`, this is a Rust-side property — set it on the
    /// call, not on per-language overrides. Per-language overrides remain
    /// supported for backwards compatibility.
    #[serde(default)]
    pub result_is_vec: bool,
    /// When `true` (combined with `result_is_simple`), the simple return is a
    /// slice/array (e.g., `Vec<String>` → `string[]` in TS).
    #[serde(default)]
    pub result_is_array: bool,
    /// When `true`, the function returns a raw byte array (`Vec<u8>` →
    /// `Uint8Array` / `[]byte` / `byte[]`).
    #[serde(default)]
    pub result_is_bytes: bool,
    /// Three-valued opt-in/out for streaming-virtual-field auto-detection.
    ///
    /// - `Some(true)`: force streaming semantics regardless of fixture shape.
    /// - `Some(false)`: disable streaming auto-detection — assertions referencing
    ///   fields like `chunks` / `chunks.length` / `tool_calls` / `finish_reason`
    ///   are treated as plain field accessors on the result, not streaming
    ///   adapters. Use this when your API has a `chunks` field that is a regular
    ///   list (not an async stream).
    /// - `None` (default): auto-detect — treat as streaming when either the
    ///   fixture provides a streaming `mock_response` or any assertion references
    ///   a hard-coded streaming-virtual-field name.
    #[serde(default)]
    pub streaming: Option<bool>,
    /// When `true`, the function returns `Option<T>`.
    #[serde(default)]
    pub result_is_option: bool,
    /// Automatic fixture-routing condition.
    ///
    /// When set, a fixture whose `call` field is `None` is routed to this named call config
    /// if the condition is satisfied.  This avoids the need to tag every fixture with
    /// `"call": "batch_scrape"` when the fixture shape already identifies the call.
    ///
    /// Example (`alef.toml`):
    /// ```toml
    /// [e2e.calls.batch_scrape]
    /// select_when = { input_has = "batch_urls" }
    /// ```
    #[serde(default)]
    pub select_when: Option<SelectWhen>,
}

fn default_result_var() -> String {
    "result".to_string()
}

fn default_returns_result() -> bool {
    false
}

/// Condition for auto-selecting a named call config when the fixture matches.
///
/// When a fixture does not specify `"call"`, the codegen normally uses the default
/// `[e2e.call]`.  A `SelectWhen` condition on a named call allows automatic routing
/// based on the fixture's id, category, tags, or input shape.  All set fields must
/// match (logical AND); a condition with no fields set never matches.
///
/// ```toml
/// [e2e.calls.batch_scrape]
/// select_when = { input_has = "batch_urls" }
///
/// [e2e.calls.crawl]
/// select_when = { category = "crawl" }
///
/// [e2e.calls.batch_crawl_stream]
/// select_when = { category = "stream", id_prefix = "batch_crawl_stream" }
/// ```
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
pub struct SelectWhen {
    /// Match when the fixture's resolved category equals this string.
    #[serde(default)]
    pub category: Option<String>,
    /// Match when the fixture's id starts with this prefix.
    #[serde(default)]
    pub id_prefix: Option<String>,
    /// Match when the fixture's id matches this simple glob.
    ///
    /// Only `*` (matches any run of characters) is supported. Use `id_prefix`
    /// for plain prefix matches.
    #[serde(default)]
    pub id_glob: Option<String>,
    /// Match when the fixture's tags include this tag.
    #[serde(default)]
    pub tag: Option<String>,
    /// Match when the fixture's input object contains this key with a non-null value.
    #[serde(default)]
    pub input_has: Option<String>,
}

impl SelectWhen {
    /// Returns true when every set discriminator matches the fixture.
    ///
    /// A `SelectWhen` with all fields `None` returns `false` — at least one
    /// discriminator must be set for the condition to fire.
    pub fn matches(
        &self,
        fixture_id: &str,
        fixture_category: &str,
        fixture_tags: &[String],
        fixture_input: &serde_json::Value,
    ) -> bool {
        let any_set = self.category.is_some()
            || self.id_prefix.is_some()
            || self.id_glob.is_some()
            || self.tag.is_some()
            || self.input_has.is_some();
        if !any_set {
            return false;
        }
        if let Some(cat) = &self.category
            && cat.as_str() != fixture_category
        {
            return false;
        }
        if let Some(prefix) = &self.id_prefix
            && !fixture_id.starts_with(prefix.as_str())
        {
            return false;
        }
        if let Some(glob) = &self.id_glob
            && !glob_matches(glob, fixture_id)
        {
            return false;
        }
        if let Some(tag) = &self.tag
            && !fixture_tags.iter().any(|t| t == tag)
        {
            return false;
        }
        if let Some(key) = &self.input_has {
            let val = fixture_input.get(key.as_str()).unwrap_or(&serde_json::Value::Null);
            if val.is_null() {
                return false;
            }
        }
        true
    }
}

/// Minimal glob matcher supporting `*` (greedy any-run) only.
fn glob_matches(pattern: &str, text: &str) -> bool {
    if !pattern.contains('*') {
        return pattern == text;
    }
    let parts: Vec<&str> = pattern.split('*').collect();
    let mut cursor = 0usize;
    for (idx, part) in parts.iter().enumerate() {
        if part.is_empty() {
            continue;
        }
        if idx == 0 {
            if !text[cursor..].starts_with(part) {
                return false;
            }
            cursor += part.len();
        } else if idx + 1 == parts.len() && !pattern.ends_with('*') {
            return text[cursor..].ends_with(part);
        } else {
            match text[cursor..].find(part) {
                Some(pos) => cursor += pos + part.len(),
                None => return false,
            }
        }
    }
    true
}

/// Maps a fixture input field to a function argument.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ArgMapping {
    /// Argument name in the function signature.
    pub name: String,
    /// JSON field path in the fixture's `input` object.
    pub field: String,
    /// Type hint for code generation.
    #[serde(rename = "type", default = "default_arg_type")]
    pub arg_type: String,
    /// Whether this argument is optional.
    #[serde(default)]
    pub optional: bool,
    /// When `true`, the Rust codegen passes this argument by value (owned) rather than
    /// by reference. Use for `Vec<T>` parameters that do not accept `&Vec<T>`.
    #[serde(default)]
    pub owned: bool,
    /// For `json_object` args targeting `&[T]` Rust parameters, set to the element type
    /// (e.g. `"f32"`, `"String"`) so the codegen emits `Vec<element_type>` annotation.
    #[serde(default)]
    pub element_type: Option<String>,
    /// Override the Go slice element type for `json_object` array args.
    ///
    /// When set, the Go e2e codegen uses this as the element type instead of the default
    /// derived from `element_type`. Use Go-idiomatic type names including the import alias
    /// prefix where needed, e.g. `"kreuzberg.BatchBytesItem"` or `"string"`.
    #[serde(default)]
    pub go_type: Option<String>,
}

fn default_arg_type() -> String {
    "string".to_string()
}

/// Per-language override for function call configuration.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct CallOverride {
    /// Override the module/import path.
    #[serde(default)]
    pub module: Option<String>,
    /// Override the function name.
    #[serde(default)]
    pub function: Option<String>,
    /// Maps canonical argument names to language-specific argument names.
    ///
    /// Used when a language binding uses a different parameter name than the
    /// canonical `args` list in `CallConfig`. For example, if the canonical
    /// arg name is `doc` but the Python binding uses `html`, specify:
    ///
    /// ```toml
    /// [e2e.call.overrides.python]
    /// arg_name_map = { doc = "html" }
    /// ```
    ///
    /// The key is the canonical name (from `args[].name`) and the value is the
    /// name to use when emitting the keyword argument in generated tests.
    #[serde(default)]
    pub arg_name_map: HashMap<String, String>,
    /// Override the crate name (Rust only).
    #[serde(default)]
    pub crate_name: Option<String>,
    /// Override the class name (Java/C# only).
    #[serde(default)]
    pub class: Option<String>,
    /// Import alias (Go only, e.g., `htmd`).
    #[serde(default)]
    pub alias: Option<String>,
    /// C header file name (C only).
    #[serde(default)]
    pub header: Option<String>,
    /// FFI symbol prefix (C only).
    #[serde(default)]
    pub prefix: Option<String>,
    /// For json_object args: the constructor to use instead of raw dict/object.
    /// E.g., "ConversionOptions" — generates `ConversionOptions(**options)` in Python,
    /// `new ConversionOptions(options)` in TypeScript.
    #[serde(default)]
    pub options_type: Option<String>,
    /// How to pass json_object args: "kwargs" (default), "dict", "json", or "from_json".
    ///
    /// - `"kwargs"`: construct `OptionsType(key=val, ...)` (requires `options_type`).
    /// - `"dict"`: pass as a plain dict/object literal `{"key": "val"}`.
    /// - `"json"`: pass via `json.loads('...')` / `JSON.parse('...')`.
    /// - `"from_json"`: call `OptionsType.from_json('...')` (Python only, PyO3 native types).
    #[serde(default)]
    pub options_via: Option<String>,
    /// Module to import `options_type` from when `options_via = "from_json"`.
    ///
    /// When set, a separate `from {from_json_module} import {options_type}` line
    /// is emitted instead of including the type in the main module import.
    /// E.g., `"liter_llm._internal_bindings"` for PyO3 native types.
    #[serde(default)]
    pub from_json_module: Option<String>,
    /// Override whether the call is async for this language.
    ///
    /// When set, takes precedence over the call-level `async` flag.
    /// Useful when a language binding uses a different async model — for example,
    /// a Python binding that returns a sync iterator from a function marked
    /// `async = true` at the call level.
    #[serde(default, rename = "async")]
    pub r#async: Option<bool>,
    /// Maps fixture option field names to their enum type names.
    /// E.g., `{"headingStyle": "HeadingStyle", "codeBlockStyle": "CodeBlockStyle"}`.
    /// The generator imports these types and maps string values to enum constants.
    #[serde(default)]
    pub enum_fields: HashMap<String, String>,
    /// Maps result-type field names to their enum type names for assertion routing.
    /// Per-call so e.g. `BatchObject.status` (enum) and `ResponseObject.status` (string)
    /// can be disambiguated.
    #[serde(default)]
    pub assert_enum_fields: HashMap<String, String>,
    /// Module to import enum types from (if different from the main module).
    /// E.g., "html_to_markdown._html_to_markdown" for PyO3 native enums.
    #[serde(default)]
    pub enum_module: Option<String>,
    /// Maps nested fixture object field names to their C# type names.
    /// Used to generate `JsonSerializer.Deserialize<NestedType>(...)` for nested objects.
    /// E.g., `{"preprocessing": "PreprocessingOptions"}`.
    #[serde(default)]
    pub nested_types: HashMap<String, String>,
    /// When `false`, nested config builder results are passed directly to builder methods
    /// without wrapping in `Optional.of(...)`. Set to `false` for bindings where nested
    /// option types are non-optional (e.g., html-to-markdown Java).
    /// Defaults to `true` for backward compatibility.
    #[serde(default = "default_true")]
    pub nested_types_optional: bool,
    /// When `true`, the function returns a simple type (e.g., `String`) rather
    /// than a struct.  Generators that would normally emit `result.content`
    /// (or equivalent field access) will use the result variable directly.
    #[serde(default)]
    pub result_is_simple: bool,
    /// When `true` (and combined with `result_is_simple`), the simple result is
    /// a slice/array type (e.g., `[]string` in Go, `Vec<String>` in Rust).
    /// The Go generator uses `strings.Join(value, " ")` for `contains` assertions
    /// instead of `string(value)`.
    #[serde(default)]
    pub result_is_array: bool,
    /// When `true`, the function returns `Vec<T>` rather than a single value.
    /// Field-path assertions are emitted as `.iter().all(|r| <accessor>)` so
    /// every element is checked. (Rust generator.)
    #[serde(default)]
    pub result_is_vec: bool,
    /// When `true`, the function returns a raw byte array (e.g., `byte[]` in Java,
    /// `[]byte` in Go). Used by generators to select the correct length accessor
    /// (field `.length` vs method `.length()`).
    #[serde(default)]
    pub result_is_bytes: bool,
    /// When `true`, the function returns `Option<T>`. The result is unwrapped
    /// before any non-`is_none`/`is_some` assertion runs; `is_empty`/`not_empty`
    /// assertions map to `is_none()`/`is_some()`. (Rust generator.)
    #[serde(default)]
    pub result_is_option: bool,
    /// When `true`, the R generator emits the call result directly without wrapping
    /// in `jsonlite::fromJSON()`. Use when the R binding already returns a native
    /// R list (`Robj`) rather than a JSON string. Field-path assertions still use
    /// `result$field` accessor syntax (i.e. `result_is_simple` behaviour is NOT
    /// implied — only the JSON parse wrapper is suppressed). (R generator only.)
    #[serde(default)]
    pub result_is_r_list: bool,
    /// When `true`, the Zig generator treats the result as a `[]u8` JSON string
    /// representing a struct value (e.g., `ExtractionResult` serialized via the
    /// FFI `_to_json` helper). The generator parses the JSON with
    /// `std.json.parseFromSlice(std.json.Value, ...)` before emitting field
    /// assertions, traversing the dynamic JSON object for each field path.
    /// (Zig generator only.)
    #[serde(default)]
    pub result_is_json_struct: bool,
    /// When `true`, the Rust generator wraps the `json_object` argument expression
    /// in `Some(...).clone()` to match an owned `Option<T>` parameter slot rather
    /// than passing `&options`. (Rust generator only.)
    #[serde(default)]
    pub wrap_options_in_some: bool,
    /// Trailing positional arguments appended verbatim after the configured
    /// `args`. Used when the target function takes additional positional slots
    /// (e.g. visitor) the fixture cannot supply directly. (Rust generator only.)
    #[serde(default)]
    pub extra_args: Vec<String>,
    /// Per-rust override of the call-level `returns_result`. When set, takes
    /// precedence over `CallConfig.returns_result` for the Rust generator only.
    /// Useful when one binding is fallible while others are not.
    #[serde(default)]
    pub returns_result: Option<bool>,
    /// Maps handle config field names to their Python type constructor names.
    ///
    /// When the handle config object contains a nested dict-valued field, the
    /// generator will wrap it in the specified type using keyword arguments.
    /// E.g., `{"browser": "BrowserConfig"}` generates `BrowserConfig(mode="auto")`
    /// instead of `{"mode": "auto"}`.
    #[serde(default)]
    pub handle_nested_types: HashMap<String, String>,
    /// Handle config fields whose type constructor takes a single dict argument
    /// instead of keyword arguments.
    ///
    /// E.g., `["auth"]` means `AuthConfig({"type": "basic", ...})` instead of
    /// `AuthConfig(type="basic", ...)`.
    #[serde(default)]
    pub handle_dict_types: HashSet<String>,
    /// Elixir struct module name for the handle config argument.
    ///
    /// When set, the generated Elixir handle config uses struct literal syntax
    /// (`%Module.StructType{key: val}`) instead of a plain string-keyed map.
    /// Rustler `NifStruct` requires a proper Elixir struct — plain maps are rejected.
    ///
    /// E.g., `"CrawlConfig"` generates `%Kreuzcrawl.CrawlConfig{download_assets: true}`.
    #[serde(default)]
    pub handle_struct_type: Option<String>,
    /// Handle config fields whose list values are Elixir atoms (Rustler NifUnitEnum).
    ///
    /// When a config field is a `Vec<EnumType>` in Rust, the Elixir side must pass
    /// a list of atoms (e.g., `[:image, :document]`) not strings (`["image"]`).
    /// List the field names here so the generator emits atom literals instead of strings.
    ///
    /// E.g., `["asset_types"]` generates `asset_types: [:image]` instead of `["image"]`.
    #[serde(default)]
    pub handle_atom_list_fields: HashSet<String>,
    /// WASM config class name for handle args (WASM generator only).
    ///
    /// When set, handle args are constructed using `ConfigType.default()` + setters
    /// instead of passing a plain JS object (which fails `_assertClass` validation).
    ///
    /// E.g., `"WasmCrawlConfig"` generates:
    /// ```js
    /// const engineConfig = WasmCrawlConfig.default();
    /// engineConfig.maxDepth = 1;
    /// const engine = createEngine(engineConfig);
    /// ```
    #[serde(default)]
    pub handle_config_type: Option<String>,
    /// PHP client factory method name (PHP generator only).
    ///
    /// When set, the generated PHP test instantiates a client via
    /// `ClassName::factory_method('test-key')` and calls methods on the instance
    /// instead of using static facade calls.
    ///
    /// E.g., `"createClient"` generates:
    /// ```php
    /// $client = LiterLlm::createClient('test-key');
    /// $result = $client->chat($request);
    /// ```
    #[serde(default)]
    pub php_client_factory: Option<String>,
    /// Client factory function name for instance-method languages (WASM, etc.).
    ///
    /// When set, the generated test imports this function, creates a client,
    /// and calls API methods on the instance instead of as top-level functions.
    ///
    /// E.g., `"createClient"` generates:
    /// ```typescript
    /// import { createClient } from 'pkg';
    /// const client = createClient('test-key');
    /// const result = await client.chat(request);
    /// ```
    #[serde(default)]
    pub client_factory: Option<String>,
    /// Verbatim trailing arguments appended after the fixed `("test-key", ...)` pair
    /// when calling the `client_factory` function.
    ///
    /// Use this when the factory function takes additional positional parameters
    /// beyond the API key and optional base URL that the generator would otherwise
    /// emit.  Each element is emitted verbatim, separated by `, `.
    ///
    /// Example — Gleam `create_client` takes five positional arguments:
    /// `(api_key, base_url, timeout_secs, max_retries, model_hint)`.  Set:
    /// ```toml
    /// [e2e.call.overrides.gleam]
    /// client_factory = "create_client"
    /// client_factory_trailing_args = ["option.None", "option.None", "option.None"]
    /// ```
    /// to produce `create_client("test-key", option.Some(url), option.None, option.None, option.None)`.
    #[serde(default)]
    pub client_factory_trailing_args: Vec<String>,
    /// Fields on the options object that require `BigInt()` wrapping (WASM only).
    ///
    /// `wasm_bindgen` maps Rust `u64`/`i64` to JavaScript `BigInt`. Numeric
    /// values assigned to these setters must be wrapped with `BigInt(n)`.
    ///
    /// List camelCase field names, e.g.:
    /// ```toml
    /// [e2e.call.overrides.wasm]
    /// bigint_fields = ["maxTokens", "seed"]
    /// ```
    #[serde(default)]
    pub bigint_fields: Vec<String>,
    /// Static CLI arguments appended to every invocation (brew/CLI generator only).
    ///
    /// E.g., `["--format", "json"]` appends `--format json` to every CLI call.
    #[serde(default)]
    pub cli_args: Vec<String>,
    /// Maps fixture config field names to CLI flag names (brew/CLI generator only).
    ///
    /// E.g., `{"output_format": "--format"}` generates `--format <value>` from
    /// the fixture's `output_format` input field.
    #[serde(default)]
    pub cli_flags: HashMap<String, String>,
    /// C FFI opaque result type name (C only).
    ///
    /// The PascalCase name of the result struct, without the prefix.
    /// E.g., `"ChatCompletionResponse"` for `LiterllmChatCompletionResponse*`.
    /// If not set, defaults to the function name in PascalCase.
    #[serde(default)]
    pub result_type: Option<String>,
    /// Override the argument order for this language binding.
    ///
    /// Lists argument names from `args` in the order they should be passed
    /// to the target function. Useful when a language binding reorders parameters
    /// relative to the canonical `args` list in `CallConfig`.
    ///
    /// E.g., if `args = [path, mime_type, config]` but the Node.js binding
    /// takes `(path, config, mime_type?)`, specify:
    /// ```toml
    /// [e2e.call.overrides.node]
    /// arg_order = ["path", "config", "mime_type"]
    /// ```
    #[serde(default)]
    pub arg_order: Vec<String>,
    /// When `true`, `json_object` args with an `options_type` are passed as a
    /// pointer (`*OptionsType`) rather than a value.  Use for Go bindings where
    /// the options parameter is `*ConversionOptions` (nil-able pointer) rather
    /// than a plain struct.
    ///
    /// Absent options are passed as `nil`; present options are unmarshalled into
    /// a local variable and passed as `&optionsVar`.
    #[serde(default)]
    pub options_ptr: bool,
    /// Alternative function name to use when the fixture includes a `visitor`.
    ///
    /// Some bindings expose two entry points: `Convert(html, opts)` for the
    /// plain case and `ConvertWithVisitor(html, opts, visitor)` when a visitor
    /// is involved.  Set this to the visitor-accepting function name so the
    /// generator can pick the right symbol automatically.
    ///
    /// E.g., `"ConvertWithVisitor"` makes the Go generator emit:
    /// ```go
    /// result, err := htmd.ConvertWithVisitor(html, nil, visitor)
    /// ```
    /// instead of `htmd.Convert(html, nil, visitor)` (which would not compile).
    #[serde(default)]
    pub visitor_function: Option<String>,
    /// Rust trait names to import when `client_factory` is set (Rust generator only).
    ///
    /// When `client_factory` is set, the generated test creates a client object and
    /// calls methods on it. Those methods are defined on traits (e.g. `LlmClient`,
    /// `FileClient`) that must be in scope. List the trait names here and the Rust
    /// generator will emit `use {module}::{trait_name};` for each.
    ///
    /// E.g.:
    /// ```toml
    /// [e2e.call.overrides.rust]
    /// client_factory = "create_client"
    /// trait_imports = ["LlmClient", "FileClient", "BatchClient", "ResponseClient"]
    /// ```
    #[serde(default)]
    pub trait_imports: Vec<String>,
    /// Raw C return type, used verbatim instead of `{PREFIX}Type*` (C only).
    ///
    /// Valid values: `"char*"`, `"int32_t"`, `"uintptr_t"`.
    /// When set, the C generator skips options handle construction and uses the
    /// raw type directly. Free logic is adjusted accordingly.
    #[serde(default)]
    pub raw_c_result_type: Option<String>,
    /// Free function for raw `char*` C results (C only).
    ///
    /// Defaults to `{prefix}_free_string` when unset and `raw_c_result_type == "char*"`.
    #[serde(default)]
    pub c_free_fn: Option<String>,
    /// C FFI engine factory pattern (C only).
    ///
    /// When set, the C generator wraps each test call in a
    /// `{prefix}_create_engine(config)` / `{prefix}_crawl_engine_handle_free(engine)`
    /// prologue/epilogue using the named config type as the "arg 0" handle type.
    ///
    /// The value is the PascalCase config type name (without prefix), e.g.
    /// `"CrawlConfig"`. The generator will emit:
    /// ```c
    /// KCRAWLCrawlConfig* config_handle = kcrawl_crawl_config_from_json("{json}");
    /// KCRAWLCrawlEngineHandle* engine = kcrawl_create_engine(config_handle);
    /// kcrawl_crawl_config_free(config_handle);
    /// KCRAWLScrapeResult* result = kcrawl_scrape(engine, url);
    /// // ... assertions ...
    /// kcrawl_scrape_result_free(result);
    /// kcrawl_crawl_engine_handle_free(engine);
    /// ```
    #[serde(default)]
    pub c_engine_factory: Option<String>,
    /// Fields in a `json_object` arg that must be wrapped in `java.nio.file.Path.of()`
    /// (Java generator only).
    ///
    /// E.g., `["cache_dir"]` wraps the string value of `cache_dir` so the builder
    /// receives `java.nio.file.Path.of("/tmp/dir")` instead of a plain string.
    #[serde(default)]
    pub path_fields: Vec<String>,
    /// Trait name for the visitor pattern (Rust e2e tests only).
    ///
    /// When a fixture declares a `visitor` block, the Rust e2e generator emits
    /// `impl <trait_name> for _TestVisitor { ... }` and imports the trait from
    /// `{module}::visitor`. When unset, no visitor block is emitted and fixtures
    /// that declare a visitor will cause a codegen error.
    ///
    /// E.g., `"HtmlVisitor"` generates:
    /// ```rust,ignore
    /// use html_to_markdown_rs::visitor::{HtmlVisitor, NodeContext, VisitResult};
    /// // ...
    /// impl HtmlVisitor for _TestVisitor { ... }
    /// ```
    #[serde(default)]
    pub visitor_trait: Option<String>,
    /// Maps result field paths to their wasm-bindgen enum class names.
    ///
    /// wasm-bindgen exposes Rust enums as numeric discriminants in JavaScript
    /// (`WasmFinishReason.Stop === 0`), not string variants. When an `equals`
    /// assertion targets a field listed here, the WASM generator emits
    /// `expect(result.choices[0].finishReason).toBe(WasmFinishReason.Stop)`
    /// instead of attempting `(value ?? "").trim()`.
    ///
    /// The fixture's expected string value is converted to PascalCase to look
    /// up the variant (e.g. `"tool_calls"` -> `ToolCalls`).
    ///
    /// Example:
    /// ```toml
    /// [e2e.calls.chat.overrides.wasm]
    /// result_enum_fields = { "choices[0].finish_reason" = "WasmFinishReason", "status" = "WasmBatchStatus" }
    /// ```
    #[serde(default)]
    pub result_enum_fields: HashMap<String, String>,
}

fn default_true() -> bool {
    true
}

/// Per-language package reference configuration.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct PackageRef {
    /// Package/crate/gem/module name.
    #[serde(default)]
    pub name: Option<String>,
    /// Relative path from e2e/{lang}/ to the package.
    #[serde(default)]
    pub path: Option<String>,
    /// Go module path.
    #[serde(default)]
    pub module: Option<String>,
    /// Package version (e.g., for go.mod require directives).
    #[serde(default)]
    pub version: Option<String>,
}

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

    fn empty_e2e_with_test_documents(dir: &str) -> E2eConfig {
        E2eConfig {
            test_documents_dir: dir.to_string(),
            ..Default::default()
        }
    }

    #[test]
    fn test_documents_dir_default_is_test_documents() {
        let cfg: E2eConfig = toml::from_str("[call]\nfunction = \"f\"\n").expect("minimal TOML must deserialize");
        assert_eq!(cfg.test_documents_dir, "test_documents");
    }

    #[test]
    fn test_documents_dir_explicit_override_wins() {
        let cfg: E2eConfig = toml::from_str("test_documents_dir = \"fixture_files\"\n[call]\nfunction = \"f\"\n")
            .expect("explicit override must deserialize");
        assert_eq!(cfg.test_documents_dir, "fixture_files");
    }

    #[test]
    fn test_documents_relative_from_at_lang_root_returns_two_dots_up() {
        let cfg = empty_e2e_with_test_documents("test_documents");
        assert_eq!(cfg.test_documents_relative_from(0), "../../test_documents");
    }

    #[test]
    fn test_documents_relative_from_at_spec_depth_returns_three_dots_up() {
        let cfg = empty_e2e_with_test_documents("test_documents");
        assert_eq!(cfg.test_documents_relative_from(1), "../../../test_documents");
    }

    #[test]
    fn test_documents_relative_from_at_two_subdirs_deep_returns_four_dots_up() {
        let cfg = empty_e2e_with_test_documents("test_documents");
        assert_eq!(cfg.test_documents_relative_from(2), "../../../../test_documents");
    }

    #[test]
    fn test_documents_relative_uses_configured_dir_name() {
        let cfg = empty_e2e_with_test_documents("fixture_files");
        assert_eq!(cfg.test_documents_relative_from(0), "../../fixture_files");
        assert_eq!(cfg.test_documents_relative_from(1), "../../../fixture_files");
    }

    #[test]
    fn select_when_with_no_discriminators_never_matches() {
        let sel = SelectWhen::default();
        assert!(!sel.matches("any_id", "any_category", &[], &serde_json::Value::Null));
    }

    #[test]
    fn select_when_input_has_matches_non_null_key() {
        let sel = SelectWhen {
            input_has: Some("batch_urls".to_string()),
            ..Default::default()
        };
        let input = serde_json::json!({ "batch_urls": [] });
        assert!(sel.matches("fid", "cat", &[], &input));
        let empty_input = serde_json::json!({ "url": "x" });
        assert!(!sel.matches("fid", "cat", &[], &empty_input));
    }

    #[test]
    fn select_when_category_matches_exactly() {
        let sel = SelectWhen {
            category: Some("crawl".to_string()),
            ..Default::default()
        };
        assert!(sel.matches("any_id", "crawl", &[], &serde_json::Value::Null));
        assert!(!sel.matches("any_id", "scrape", &[], &serde_json::Value::Null));
    }

    #[test]
    fn select_when_id_prefix_matches() {
        let sel = SelectWhen {
            id_prefix: Some("batch_crawl_".to_string()),
            ..Default::default()
        };
        assert!(sel.matches("batch_crawl_events", "any", &[], &serde_json::Value::Null));
        assert!(!sel.matches("batch_scrape_basic", "any", &[], &serde_json::Value::Null));
    }

    #[test]
    fn select_when_id_glob_handles_star() {
        let sel = SelectWhen {
            id_glob: Some("crawl_stream*".to_string()),
            ..Default::default()
        };
        assert!(sel.matches("crawl_stream_basic", "any", &[], &serde_json::Value::Null));
        assert!(!sel.matches("batch_crawl_stream", "any", &[], &serde_json::Value::Null));
    }

    #[test]
    fn select_when_tag_matches_any_tag_in_list() {
        let sel = SelectWhen {
            tag: Some("streaming".to_string()),
            ..Default::default()
        };
        let tags = vec!["smoke".to_string(), "streaming".to_string()];
        assert!(sel.matches("fid", "cat", &tags, &serde_json::Value::Null));
        assert!(!sel.matches("fid", "cat", &["smoke".to_string()], &serde_json::Value::Null));
    }

    #[test]
    fn select_when_multiple_discriminators_anded() {
        let sel = SelectWhen {
            category: Some("stream".to_string()),
            id_prefix: Some("batch_crawl_stream".to_string()),
            ..Default::default()
        };
        assert!(sel.matches("batch_crawl_stream_events", "stream", &[], &serde_json::Value::Null));
        // Wrong category fails even though prefix matches
        assert!(!sel.matches("batch_crawl_stream_events", "crawl", &[], &serde_json::Value::Null));
        // Wrong prefix fails even though category matches
        assert!(!sel.matches("crawl_stream_basic", "stream", &[], &serde_json::Value::Null));
    }

    #[test]
    fn select_when_deserializes_legacy_input_has_only() {
        let toml_src = r#"
            [call]
            function = "scrape"

            [calls.batch_scrape]
            function = "batch_scrape"
            select_when = { input_has = "batch_urls" }
        "#;
        let cfg: E2eConfig = toml::from_str(toml_src).expect("legacy input_has must deserialize");
        let sel = cfg.calls["batch_scrape"].select_when.as_ref().unwrap();
        assert_eq!(sel.input_has.as_deref(), Some("batch_urls"));
        assert!(sel.category.is_none());
        assert!(sel.id_prefix.is_none());
    }

    #[test]
    fn select_when_deserializes_compound_discriminators() {
        let toml_src = r#"
            [call]
            function = "scrape"

            [calls.batch_crawl_stream]
            function = "batch_crawl_stream"
            select_when = { category = "stream", id_prefix = "batch_crawl_stream" }
        "#;
        let cfg: E2eConfig = toml::from_str(toml_src).expect("compound select_when must deserialize");
        let sel = cfg.calls["batch_crawl_stream"].select_when.as_ref().unwrap();
        assert_eq!(sel.category.as_deref(), Some("stream"));
        assert_eq!(sel.id_prefix.as_deref(), Some("batch_crawl_stream"));
    }

    #[test]
    fn resolve_call_for_fixture_routes_by_category_then_falls_back() {
        let mut calls = HashMap::new();
        calls.insert(
            "crawl".to_string(),
            CallConfig {
                function: "crawl".to_string(),
                select_when: Some(SelectWhen {
                    category: Some("crawl".to_string()),
                    ..Default::default()
                }),
                ..Default::default()
            },
        );
        let cfg = E2eConfig {
            call: CallConfig {
                function: "scrape".to_string(),
                ..Default::default()
            },
            calls,
            ..Default::default()
        };
        let input = serde_json::json!({ "url": "https://example.com" });
        let resolved = cfg.resolve_call_for_fixture(None, "crawl_basic", "crawl", &[], &input);
        assert_eq!(resolved.function, "crawl");
        let resolved = cfg.resolve_call_for_fixture(None, "scrape_basic", "scrape", &[], &input);
        assert_eq!(resolved.function, "scrape");
    }

    // --- effective_* resolver helpers ---

    #[test]
    fn effective_result_fields_returns_global_when_call_is_empty() {
        let mut global = HashSet::new();
        global.insert("url".to_string());
        let cfg = E2eConfig {
            result_fields: global.clone(),
            ..Default::default()
        };
        let call = CallConfig::default();
        assert_eq!(cfg.effective_result_fields(&call), &global);
    }

    #[test]
    fn effective_result_fields_call_override_wins_over_global() {
        let mut global = HashSet::new();
        global.insert("url".to_string());
        let mut per_call = HashSet::new();
        per_call.insert("pages".to_string());
        per_call.insert("final_url".to_string());
        let cfg = E2eConfig {
            result_fields: global,
            ..Default::default()
        };
        let call = CallConfig {
            result_fields: per_call.clone(),
            ..Default::default()
        };
        assert_eq!(cfg.effective_result_fields(&call), &per_call);
    }

    #[test]
    fn effective_fields_returns_global_when_call_is_empty() {
        let mut global = HashMap::new();
        global.insert("metadata.title".to_string(), "metadata.document.title".to_string());
        let cfg = E2eConfig {
            fields: global.clone(),
            ..Default::default()
        };
        let call = CallConfig::default();
        assert_eq!(cfg.effective_fields(&call), &global);
    }

    #[test]
    fn effective_fields_call_override_wins_over_global() {
        let mut global = HashMap::new();
        global.insert("a".to_string(), "b".to_string());
        let mut per_call = HashMap::new();
        per_call.insert("x".to_string(), "y".to_string());
        let cfg = E2eConfig {
            fields: global,
            ..Default::default()
        };
        let call = CallConfig {
            fields: per_call.clone(),
            ..Default::default()
        };
        assert_eq!(cfg.effective_fields(&call), &per_call);
    }

    #[test]
    fn effective_fields_optional_returns_global_when_call_is_empty() {
        let mut global = HashSet::new();
        global.insert("segments".to_string());
        let cfg = E2eConfig {
            fields_optional: global.clone(),
            ..Default::default()
        };
        let call = CallConfig::default();
        assert_eq!(cfg.effective_fields_optional(&call), &global);
    }

    #[test]
    fn effective_fields_optional_call_override_wins_over_global() {
        let mut global = HashSet::new();
        global.insert("segments".to_string());
        let mut per_call = HashSet::new();
        per_call.insert("pages".to_string());
        let cfg = E2eConfig {
            fields_optional: global,
            ..Default::default()
        };
        let call = CallConfig {
            fields_optional: per_call.clone(),
            ..Default::default()
        };
        assert_eq!(cfg.effective_fields_optional(&call), &per_call);
    }

    #[test]
    fn effective_fields_array_returns_global_when_call_is_empty() {
        let mut global = HashSet::new();
        global.insert("choices".to_string());
        let cfg = E2eConfig {
            fields_array: global.clone(),
            ..Default::default()
        };
        let call = CallConfig::default();
        assert_eq!(cfg.effective_fields_array(&call), &global);
    }

    #[test]
    fn effective_fields_array_call_override_wins_over_global() {
        let mut global = HashSet::new();
        global.insert("choices".to_string());
        let mut per_call = HashSet::new();
        per_call.insert("pages".to_string());
        let cfg = E2eConfig {
            fields_array: global,
            ..Default::default()
        };
        let call = CallConfig {
            fields_array: per_call.clone(),
            ..Default::default()
        };
        assert_eq!(cfg.effective_fields_array(&call), &per_call);
    }

    #[test]
    fn effective_fields_method_calls_returns_global_when_call_is_empty() {
        let mut global = HashSet::new();
        global.insert("metadata.format".to_string());
        let cfg = E2eConfig {
            fields_method_calls: global.clone(),
            ..Default::default()
        };
        let call = CallConfig::default();
        assert_eq!(cfg.effective_fields_method_calls(&call), &global);
    }

    #[test]
    fn effective_fields_method_calls_call_override_wins_over_global() {
        let mut global = HashSet::new();
        global.insert("metadata.format".to_string());
        let mut per_call = HashSet::new();
        per_call.insert("pages.status".to_string());
        let cfg = E2eConfig {
            fields_method_calls: global,
            ..Default::default()
        };
        let call = CallConfig {
            fields_method_calls: per_call.clone(),
            ..Default::default()
        };
        assert_eq!(cfg.effective_fields_method_calls(&call), &per_call);
    }

    #[test]
    fn effective_fields_enum_returns_global_when_call_is_empty() {
        let mut global = HashSet::new();
        global.insert("choices.finish_reason".to_string());
        let cfg = E2eConfig {
            fields_enum: global.clone(),
            ..Default::default()
        };
        let call = CallConfig::default();
        assert_eq!(cfg.effective_fields_enum(&call), &global);
    }

    #[test]
    fn effective_fields_enum_call_override_wins_over_global() {
        let mut global = HashSet::new();
        global.insert("choices.finish_reason".to_string());
        let mut per_call = HashSet::new();
        per_call.insert("assets.category".to_string());
        let cfg = E2eConfig {
            fields_enum: global,
            ..Default::default()
        };
        let call = CallConfig {
            fields_enum: per_call.clone(),
            ..Default::default()
        };
        assert_eq!(cfg.effective_fields_enum(&call), &per_call);
    }

    #[test]
    fn effective_fields_c_types_returns_global_when_call_is_empty() {
        let mut global = HashMap::new();
        global.insert("conversion_result.metadata".to_string(), "HtmlMetadata".to_string());
        let cfg = E2eConfig {
            fields_c_types: global.clone(),
            ..Default::default()
        };
        let call = CallConfig::default();
        assert_eq!(cfg.effective_fields_c_types(&call), &global);
    }

    #[test]
    fn effective_fields_c_types_call_override_wins_over_global() {
        let mut global = HashMap::new();
        global.insert("conversion_result.metadata".to_string(), "HtmlMetadata".to_string());
        let mut per_call = HashMap::new();
        per_call.insert("crawl_result.pages".to_string(), "PageResult".to_string());
        let cfg = E2eConfig {
            fields_c_types: global,
            ..Default::default()
        };
        let call = CallConfig {
            fields_c_types: per_call.clone(),
            ..Default::default()
        };
        assert_eq!(cfg.effective_fields_c_types(&call), &per_call);
    }

    #[test]
    fn effective_resolver_helpers_deserialize_from_toml() {
        let toml = r#"
[call]
function = "scrape"
result_fields = ["url", "markdown"]
fields_enum = ["status"]

[call.fields]
"meta.title" = "meta.document.title"

[call.fields_c_types]
"scrape_result.meta" = "MetaResult"
"#;
        let cfg: E2eConfig = toml::from_str(toml).expect("must deserialize");
        let call = &cfg.call;
        assert!(cfg.effective_result_fields(call).contains("url"));
        assert!(cfg.effective_result_fields(call).contains("markdown"));
        assert!(cfg.effective_fields_enum(call).contains("status"));
        assert_eq!(
            cfg.effective_fields(call).get("meta.title").map(String::as_str),
            Some("meta.document.title")
        );
        assert_eq!(
            cfg.effective_fields_c_types(call)
                .get("scrape_result.meta")
                .map(String::as_str),
            Some("MetaResult")
        );
    }
}